Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 列表中列表元素的组合_Python_List - Fatal编程技术网

Python 列表中列表元素的组合

Python 列表中列表元素的组合,python,list,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)

我需要以下输出:[[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

使用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]]

使用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]]

或者
[x代表产品中的c(flag_2,repeat=2)代表c中的x]
@roippi:为什么需要周围的
[]
?@wap26这是一个列表理解。这就是语法。@roippi:是的,很明显。我看错了你的答案。或者
[x代表产品中的c(flag_2,repeat=2)代表c中的x]
@roippi:你为什么需要周围的
[]
?@wap26这是一个列表理解。这就是语法。@roippi:是的,很明显。我误解了你的答案。