使用带有itertools.product的n-lists生成元组

时间:2013-11-02 15:43:52

标签: python python-2.7 itertools cartesian-product

如果我不知道列表的数量,我该如何使用itertools.product功能?我有列表,里面有列表。

喜欢,

lis = [[1,2,3],[6,7,8],[2,4,5]]

通常我需要这样做,

product([1,2,3],[6,7,8],[2,4,5])

如果输入是示例中的列表,我该怎么做?

2 个答案:

答案 0 :(得分:1)

使用argument unpacking

>>> lis = [[1,2,3],[6,7,8],[2,4,5]]
>>> list(itertools.product(*lis))
[(1, 6, 2), (1, 6, 4), (1, 6, 5), (1, 7, 2), (1, 7, 4), (1, 7, 5), (1, 8, 2),
 (1, 8, 4), (1, 8, 5), (2, 6, 2), (2, 6, 4), (2, 6, 5), (2, 7, 2), (2, 7, 4),
 (2, 7, 5), (2, 8, 2), (2, 8, 4), (2, 8, 5), (3, 6, 2), (3, 6, 4), (3, 6, 5),
 (3, 7, 2), (3, 7, 4), (3, 7, 5), (3, 8, 2), (3, 8, 4), (3, 8, 5)]
>>>

答案 1 :(得分:1)

请尝试以下方法:
product(*lis)
它被称为argument unpacking 简短说明:您也可以使用带有命名参数的参数解包,使用双星:

def simpleSum(a=1,b=2):
    return a + b
simpleSum(**{'a':1,'b':2}) # returns 3