我基本上是在寻找一个python版本的组合列表<列表<int>>
给定一个列表的列表,我需要一个新的列表,它给出列表之间所有可能的项目组合。
[[1,2,3],[4,5,6],[7,8,9,10]] -> [[1,4,7],[1,4,8],...,[3,6,10]]
列表的数量是未知的,所以我需要对所有情况都适用的东西。优雅的加分!
我基本上是在寻找一个python版本的组合列表<列表<int>>
给定一个列表的列表,我需要一个新的列表,它给出列表之间所有可能的项目组合。
[[1,2,3],[4,5,6],[7,8,9,10]] -> [[1,4,7],[1,4,8],...,[3,6,10]]
列表的数量是未知的,所以我需要对所有情况都适用的东西。优雅的加分!
当前回答
对于这个任务,直接递归没有错,不需要外部依赖,如果你需要一个处理字符串的版本,这可能适合你的需求:
combinations = []
def combine(terms, accum):
last = (len(terms) == 1)
n = len(terms[0])
for i in range(n):
item = accum + terms[0][i]
if last:
combinations.append(item)
else:
combine(terms[1:], item)
>>> a = [['ab','cd','ef'],['12','34','56']]
>>> combine(a, '')
>>> print(combinations)
['ab12', 'ab34', 'ab56', 'cd12', 'cd34', 'cd56', 'ef12', 'ef34', 'ef56']
其他回答
只需使用itertools.product:
listOLists = [[1,2,3],[4,5,6],[7,8,9,10]]
for l in itertools.product(*listOLists):
print(l)
最优雅的解决方案是使用itertools。python 2.6中的产品。
如果你使用的不是Python 2.6, itertools的文档。Product实际上显示了一个等效的功能,做产品的“手动”方式:
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
from itertools import product
list_vals = [['Brand Acronym:CBIQ', 'Brand Acronym :KMEFIC'],['Brand Country:DXB','Brand Country:BH']]
list(product(*list_vals))
输出:
[('品牌首字母缩写:CBIQ', '品牌国家:DXB'), (“品牌首字母缩写:CBIQ”,“品牌国家:BH”), (“品牌首字母缩写:KMEFIC”,“品牌国家:DXB”), (“品牌首字母缩写:KMEFIC”,“品牌国家:BH”)]
Numpy可以做到:
>>> import numpy
>>> a = [[1,2,3],[4,5,6],[7,8,9,10]]
>>> [list(x) for x in numpy.array(numpy.meshgrid(*a)).T.reshape(-1,len(a))]
[[ 1, 4, 7], [1, 5, 7], [1, 6, 7], ....]
对于这个任务,直接递归没有错,不需要外部依赖,如果你需要一个处理字符串的版本,这可能适合你的需求:
combinations = []
def combine(terms, accum):
last = (len(terms) == 1)
n = len(terms[0])
for i in range(n):
item = accum + terms[0][i]
if last:
combinations.append(item)
else:
combine(terms[1:], item)
>>> a = [['ab','cd','ef'],['12','34','56']]
>>> combine(a, '')
>>> print(combinations)
['ab12', 'ab34', 'ab56', 'cd12', 'cd34', 'cd56', 'ef12', 'ef34', 'ef56']