[英]How to get all combination from multiple lists?
我不确定我的问题是否正确,但我不知道如何解释它。 所以我有一些清单,比如
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
, 组合:
import itertools
a = ['11', '12']
b = ['21', '22']
c = ['31', '32']
list(itertools.combinations(itertools.chain(a,b,c), 3))
[('11', '12', '21'), ('11', '12', '22'), ('11', '12', '31'), ('11', '12', '32'), ('11', '21', '22'), ('11', '21', '31'), ('11', '21', '32'), ('11', '22', '31'), ('11', '22', '32'), ('11', '31', '32'), ('12', '21', '22'), ('12', '21', '31'), ('12', '21', '32'), ('12', '22', '31'), ('12', '22', '32'), ('12', '31', '32'), ('21', '22', '31'), ('21', '22', '32'), ('21', '31', '32'), ('22', '31', '32')]
或产品:
list(itertools.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')]
您需要itertools.product来返回输入迭代的笛卡尔积。
>>> 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']]
import itertools
list(itertools.product(a,b,c))
或使用 numpy
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)
不使用任何库的解决方案:
def subproblem(list_a, list_b):
c = list()
for i, a_i in enumerate(list_a):
for j, b_j in enumerate(list_b):
c.append(a_i + [b_j])
return c
def multi_lists_find_all_combination(lists):
com = [[]]
if len(lists) == 1:
return lists[0]
for i in range(0, len(lists)):
print(i)
com = subproblem(com, lists[i])
return com
a = ['11', '12']
b = ['21', '22']
c = ['31', '32']
ans = multi_lists_find_all_combination([a,b,c])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.