2016-12-11 126 views
-4

例如,如何從列表中的元素生成所有可能的組合?

list = [0, 1, 2] 

我希望所有可能的2組合的列表:

combinations = [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)] 

在我看來,在Python中itertools所有的工具,只能使一個(1,0 )和(0,1),而不是兩個,我都需要。任何建議,除了手動輸入?

+5

您是否試過'itertools.product'? – vaultah

回答

2

你正在尋找一個笛卡爾乘積該列表與自己,而不是排列或組合。因此,您應該使用itertools.productrepeat=2

from itertools import product 

li = [0, 1, 2] 
print(list(product(li, repeat=2))) 
>> [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] 
0

可以通過導入itertools來完成:

import itertools 

list1 = [0, 1, 2] 
print(list(itertools.product(list1,repeat=2))) 

輸出:

[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] 

資源: 您可以瞭解更多關於它 - here

+0

您是否將您的輸出與OP的期望輸出進行比較? – vaultah

+0

哦,我的壞,我解決它和我的答案。 – Inconnu

+0

多次運行同一個循環沒有意義。 'itertools.combinations(list1,2)'不會產生所需的輸出。 – vaultah

相關問題