2014-12-03 116 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)] 
相關問題