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

Rig*_*ter 0 python function iterable-unpacking

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

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

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()函数。我想过将元素解压到等效的用户定义函数中,但我不知道如何对变量列表执行此操作。

我该如何定义这个函数?

Cyt*_*rak 6

我认为itertools.product在这里工作得很好,除非我错过了一些东西。

>>> from itertools import product
>>> l = [(1, 2), (3,), (5, 0)]
>>> list(product(*l))  # unpack the list of tuples into product
[(1, 3, 5), (1, 3, 0), (2, 3, 5), (2, 3, 0)]
Run Code Online (Sandbox Code Playgroud)

在 Python 中***可以用作可迭代对象的打包/解包运算符。下面是一个解包的例子:

# Suppose you have a few variables, of which one (b) is an iterable
>>> a = 1
>>> b = [2, 3, 4]
>>> c = 5

# Now you can make a new list with a, b, and c
>>> list1 = [a, b, c]
>>> list1
[1, [2, 3, 4], 5]

# Notice how b stays a list inside the new list.
# If we need the individual elements of b, we can use unpacking
>>> list2 = [a, *b, c]
>>> list2
[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)

类似地,由于product需要将可迭代对象作为单独的参数传递,我们可以使用解包。您可以在PEP 448PEP 3132中了解有关拆包的更多信息。

  • OP似乎不知道如何使用星号。我认为你应该解释一下。 (3认同)