或者等效地,如何解包可變長度序列的元素?
我正在嘗試撰寫一個函式來回傳串列中所有元組的笛卡爾積(串列具有可變長度):
Input: [(1, 2), (3,), (5, 0)]
Output: [(1, 3, 5), (1, 3, 0), (2, 3, 5), (2, 3, 0)]
但問題是我無法將所有元組傳遞給itertools.product()函式。我想在等效的用戶定義函式中解包元素,但我不知道如何為變數串列執行此操作。
我該如何定義這個函式?
uj5u.com熱心網友回復:
我認為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)]
在 Python中*,**可用作打包/解包運算子 wrt iterables。下面是一個拆包的例子:
# 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]
同樣,由于product需要將迭代作為單獨的引數傳遞,我們可以使用解包。您可以在PEP 448和PEP 3132中了解更多關于解包的資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/487555.html
上一篇:for回圈列印if陳述句的問題
下一篇:R概率中的函式
