使用itertools从2个列表生成组合

时间:2018-01-12 13:48:33

标签: python itertools

我有两个列表[1,2,3][4,5,6]。我想使用itertools

生成所有组合的列表,如下所示

ResultingList = [[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]

到目前为止,我只调查了itertools.combinations函数,它似乎只能处理这样的事情:

list(itertools.combinations([1,2,3,4,5,6],2))

哪个输出的结果不正确。如何在上方生成ResultingList

由于

3 个答案:

答案 0 :(得分:5)

使用product

>>> from itertools import product
>>> list(product([1,2,3], [4,5,6]))
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

一般理解:

正如文档中所述,product相当于: ((x,y) for x in A for y in B)其中A和B是您的输入列表

答案 1 :(得分:2)

如果您没有从itertools导入产品,那么您也可以使用这种方式

a=[1,2,3]
b=[4,5,6]
c=[]
for i in a:
    for j in b:
        c.append((i,j))
print c 

答案 2 :(得分:0)

你可以做到:

print([(i,j) for i in a for j in b])

输出:

[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
相关问题