2014-05-20 55 views
-3

我想從列表中找到所有2個項目的組合。內部列表包含一個或多個項目,我不想在同一個內部列表中包含項目的組合(除非該組合存在於單獨的內部列表中)。Python:包含1個或多個項目的列表列表中的2個項目組合

有沒有一種方法可以利用itertools中內置的函數來達到我想要的組合要求,還是我需要從頭開始編寫for循環?

這裏是一個非常簡單的例子:

x = [['219'], ['220'], ['218']] 
# find combos 
print combos 
>> [['219', '220'], ['219', '218'], ['220', '218']] 

列表可以包含列表與多個項目。下面是一個更復雜的例子,其中內部列表包含多於一個項目:

x = [['222', '219'], ['221'], ['220', '218', '216']] 
# find combos 
print combos 
>> [['222', '221'], ['222', '220'], ['222', '220'], ['222', '218'], ['222', '216'], ['219', '221'], ['219', '220'], ['219', '218'], ['219', '216'], ['221', '220'], ['221', '218'], ['221', '216']] 
+0

我應該更明確:有沒有利用內置的功能,從itertools以我所希望的組合要求到達的方式,或者我需要寫的for循環從頭開始。 – Abundnce10

+0

編輯問題更加簡潔。 – Abundnce10

回答

2

這個單線內容如何?

from itertools import combinations, product, chain 

x = [['222', '219'], ['221'], ['220', '218', '216']] 
combos = list(chain.from_iterable([list(product(a,b)) for (a,b) in combinations(x,2)])) 

編輯: roippi是絕對正確的。我們可以通過

擺脫不必要的中間體
combos = list(chain.from_iterable(product(*c) for c in combinations(x,2))) 
+3

這絕對是正確的方法,但你無用地建立了很多中間表。嘗試'list(chain.from_iterable(product(* c)for c in combination(x,2)))' – roippi

+0

感謝roippi,那就是我正在尋找的! – Abundnce10

相關問題