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
Python 如何从多个列表中获取所有组合?_Python - Fatal编程技术网

Python 如何从多个列表中获取所有组合?

Python 如何从多个列表中获取所有组合?,python,Python,我不确定我的问题是否正确,但我不知道如何用其他词来解释。 所以我有一些清单,比如 a = ['11', '12'] b = ['21', '22'] c = ['31', '32'] 我需要得到类似的东西: result = [ ['11', '21', '31'], ['11', '21', '32'], ['11', '22', '31'], ['11', '22', '32'], ['12', '21', '31'], ['12', '21

我不确定我的问题是否正确,但我不知道如何用其他词来解释。 所以我有一些清单,比如

a = ['11', '12']
b = ['21', '22']
c = ['31', '32']
我需要得到类似的东西:

result = [
    ['11', '21', '31'],
    ['11', '21', '32'],
    ['11', '22', '31'],
    ['11', '22', '32'],
    ['12', '21', '31'],
    ['12', '21', '32'],
    ['12', '22', '31'],
    ['12', '22', '32']
]

用户
itertools
,:

或:

你需要 它返回输入项的笛卡尔乘积

>>> a = ['11', '12']
>>> b = ['21', '22']
>>> c = ['31', '32']
>>>
>>> from itertools import product
>>>
>>> list(product(a,b,c))
[('11', '21', '31'), ('11', '21', '32'), ('11', '22', '31'), ('11', '22', '32'), ('12', '21', '31'), ('12', '21', '32'), ('12', '22', '31'), ('12', '22', '32')]
您可以使用列表理解将元组转换为列表:

>>> [list(i) for i in product(a,b,c)]
[['11', '21', '31'], ['11', '21', '32'], ['11', '22', '31'], ['11', '22', '32'], ['12', '21', '31'], ['12', '21', '32'], ['12', '22', '31'], ['12', '22', '32']]
或者使用numpy

import numpy
[list(x) for x in numpy.array(numpy.meshgrid(a,b,c)).T.reshape(-1,len(a))]
编辑

import numpy as np 
len = 3 #combination array length
np.array(np.meshgrid(a, b, c)).T.reshape(-1,len)

重复:请先尝试自己研究你的问题,将你的问题标题复制到谷歌会产生多个重复。如果是这样,所有列表的长度都会是两倍吗?如果是这样,它看起来像一个二进制计数系统,那么你可以用一个算法来实现这一点,但是使用itertools的帖子是正确的。
组合
留下的一些结果使用了相同列表中的两个元素。
import itertools
list(itertools.product(a,b,c))
import numpy
[list(x) for x in numpy.array(numpy.meshgrid(a,b,c)).T.reshape(-1,len(a))]
import numpy as np    
np.array(np.meshgrid(a, b, c)).T.reshape(-1,3)
import numpy as np 
len = 3 #combination array length
np.array(np.meshgrid(a, b, c)).T.reshape(-1,len)