标签: iterable-unpacking

将 NamedTuple 转换为 dict 以用于字典解包的 Pythonic 方法(**kwargs)

我有一个typing.NamedTuple我想转换为一个,dict以便我可以通过字典解包传递给一个函数:

def kwarg_func(**kwargs) -> None:
    print(kwargs)

# This doesn't actually work, I am looking for something like this
kwarg_func(**dict(my_named_tuple))
Run Code Online (Sandbox Code Playgroud)

实现这一目标的最 Pythonic 方法是什么?我正在使用 Python 3.8+。


更多细节

这是一个NamedTuple可以使用的示例:

from typing import NamedTuple

class Foo(NamedTuple):
    f: float
    b: bool = True

foo = Foo(1.0)
Run Code Online (Sandbox Code Playgroud)

尝试kwarg_func(**dict(foo))提出一个TypeError

TypeError: cannot convert dictionary update sequence element #0 to a sequence
Run Code Online (Sandbox Code Playgroud)

根据这篇文章collections.namedtuple_asdict()作品:

TypeError: cannot convert dictionary update sequence element #0 to a sequence …
Run Code Online (Sandbox Code Playgroud)

python dictionary namedtuple iterable-unpacking

0
推荐指数
1
解决办法
40
查看次数

如何将序列的所有元素传递给Python中的函数?

或者等效地,如何解压缩可变长度序列的元素?

我正在尝试编写一个函数来返回列表中所有元组的笛卡尔积(列表的长度可变):

Input: [(1, 2), (3,), (5, 0)]
Output: [(1, 3, 5), (1, 3, 0), (2, 3, 5), (2, 3, 0)]
Run Code Online (Sandbox Code Playgroud)

但问题是我无法将所有元组传递给该itertools.product()函数。我想过将元素解压到等效的用户定义函数中,但我不知道如何对变量列表执行此操作。

我该如何定义这个函数?

python function iterable-unpacking

0
推荐指数
1
解决办法
225
查看次数

解包 * 在 leetcode 上抛出语法错误

我正在解决硬币找零问题。我使用 leetcode 上的给定示例在 jupyter-notebook 上运行代码并且它工作正常。

在此处输入图片说明

相同的代码不适用于 leetcode。导致语法错误:

在此处输入图片说明

这是要复制的代码:

def best_sum(target,nums):
    dp=[None for y in range(target+1)]
    dp[0]=[]
    for i in range(len(dp)):
        if dp[i]!=None:
            for num in nums:
                if i+num<=target:
                    combination=[*dp[i],num]
                    if dp[i+num]==None or len(combination)<len(dp[i+num]):
                        dp[i+num]=combination
    return dp[-1]
best_sum(11,[1,2,5])
Run Code Online (Sandbox Code Playgroud)

python algorithm iterable-unpacking

-1
推荐指数
1
解决办法
76
查看次数

Python,这是一个bug,附加到元组中的列表会导致无吗?

这是我很长一段时间写的最短的例子之一

我创建并更新了一个元组3

In [65]: arf=(0,1,[1,2,3])

In [66]: arf=(arf[0],arf[1], arf[2] )

In [67]: arf
Out[67]: (0, 1, [1, 2, 3])
Run Code Online (Sandbox Code Playgroud)

所以重新分配工作.

现在我尝试改变它的内容.

In [69]: arf=(arf[0],arf[1], [2] )

In [70]: arf
Out[70]: (0, 1, [2])

In [71]: arf=(arf[0],arf[1], arf[2].append(3) )

In [72]: arf
Out[72]: (0, 1, None)
Run Code Online (Sandbox Code Playgroud)

我回来了吗??? 嘿,是什么给出的?对不起,我是一个蟒蛇菜鸟.

python tuples list append iterable-unpacking

-2
推荐指数
1
解决办法
845
查看次数