如何从包含m个元素的n个列表的列表中进行元素的每个组合? (蟒蛇)

时间:2014-12-03 22:35:07

标签: list python-2.7

从n个列表的列表中,每个列表都有不同数量的元素,我希望得到所有可能的组合。

我举一个例子来帮助理解我的问题:

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

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 个答案:

答案 0 :(得分: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')]

答案 1 :(得分: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)]