2014-12-03 117 views
0

从n个列表中,每个列表都有不同数量的元素,我想要获得所有可能的组合。如何使用m个元素从n个列表中列出每个元素的组合? (Python)

我打一个比方来帮助理解我的问题:

如果我有这样一个列表的列表:

a = [['a','b'], ['c','d'],['e','f','g']] 

我希望得到的东西是这样的:

[[('a', 'c', 'e')], 
[('a', 'c', 'f')], 
[('a', 'c', 'g')], 
[('a', 'd', 'e')], 
[('a', 'd', 'f')], 
[('a', 'd', 'g')], 
[('b', 'c', 'e')], 
[('b', 'c', 'f')], 
[('b', 'c', 'g')], 
[('b', 'd', 'e')], 
[('b', 'd', 'f')], 
[('b', 'd', 'g')]] 

我明白了这一点:

list((zip(x,y,z) for x in a[0] for y in a [1] for z in a[2])) 

现在我想要一个函数来对我列表中的任何列表做同样的事情。 (没有列表是空的)

that这样的递归可能可以工作,但我很难找出它,并且可能不太复杂和更快。

我在java here中发现了一个解决方案,但我不知道java,我无法翻译它。

回答

2

这里有一个itertools.product函数。只要解您的列表作为参数:

>>> from itertools import product 
>>> list(product(*a)) 
[('a', 'c', 'e'), ('a', 'c', 'f'), ('a', 'c', 'g'), ('a', 'd', 'e'), ('a', 'd', 'f'), ('a', 'd', 'g'), ('b', 'c', 'e'), ('b', 'c', 'f'), ('b', 'c', 'g'), ('b', 'd', 'e'), ('b', 'd', 'f'), ('b', 'd', 'g')] 
+0

OP祝愿在被包裹的元组我想是一个清单。 – 2014-12-03 22:47:22

+0

@JonathanEunice,我怀疑它,我认为在例子中使用它是因为这是'zip'返回的,而不是他的意图。 – zch 2014-12-03 22:51:29

+0

我同意这是完全没有必要的 - 元组应该做得像第一级容器一样好。我只是想通过“我想得到这样的东西:”接着是盒装的例子。 – 2014-12-03 22:55:54

0
from itertools import product 

[[combo] for combo in product(*a)] 

产量:

[[('a', 'c', 'e')], 
[('a', 'c', 'f')], 
[('a', 'c', 'g')], 
[('a', 'd', 'e')], 
[('a', 'd', 'f')], 
[('a', 'd', 'g')], 
[('b', 'c', 'e')], 
[('b', 'c', 'f')], 
[('b', 'c', 'g')], 
[('b', 'd', 'e')], 
[('b', 'd', 'f')], 
[('b', 'd', 'g')]] 

所以对于一个功能,你只需要:

def boxed_product(somelists): 
    return [[combo] for combo in product(*somelists)] 
相关问题