列表的列表元素的组合

时间:2013-11-23 16:36:33

标签: python list

我想要以下输出:[[1,2,1,2],[1,2,3,4],[3,4,1,2],[3,4,3,4]]但我的代码没有正常工作。

flag_2=[[1,2],[3,4]]

for i in flag_2:
        icopy = copy.copy(i)
        print "icopy",icopy
        for j in flag_2:
             temp4=[]
             jcopy = copy.copy(j)
             print "jcopy",jcopy
             temp4=copy.copy(list_extend(icopy,jcopy))
             print temp4
             temp4=[]
             print temp4

1 个答案:

答案 0 :(得分:4)

使用itertools'product获取所需的组合,chain展平结果:

from itertools import product,chain

[list(chain.from_iterable(c)) for c in product(flag_2,repeat=2)]
Out[7]: [[1, 2, 1, 2], [1, 2, 3, 4], [3, 4, 1, 2], [3, 4, 3, 4]]