2014-01-14 29 views
1

給定一個列表l=range(n),我如何迭代該列表中所有不同對的不同對。所有配對python

例如,如果l = [0,1,2,3]我想[((0,1), (0,2)),((0,1),(0,3)), ((0,1),(1,2)), ((0,1), (1,3)),((0,1), (2,3)), ((0,2), (0,3)), ((0,2),(1,2)),((0,2),(1,3)),((0,2),(2,3))...

+0

@wheaties我試着玩itertools,但我無法正確理解它。 – octonots

+2

@octnots最好,如果你顯示你寫的代碼,以便我們可以在那裏幫助。有時候,這只是一個「大腦放屁」,你做對了,其他時候你學會了一些基本的東西,讓你變得更好。 – wheaties

回答

6

您可以使用itertools.combinations:再次

>>> l = [0,1,2,3] 
>>> list(combinations(l, 2)) 
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] 

第二對他們說:

from itertools import combinations 

for pair in combinations(combinations(l, 2), 2): 
    # use pair 

第一次調用創建初始對:

>>> list(combinations(combinations(l, 2), 2)) 
[((0, 1), (0, 2)), ((0, 1), (0, 3)), ((0, 1), (1, 2)), ((0, 1), (1, 3)), 
((0, 1), (2, 3)), ((0, 2), (0, 3)), ((0, 2), (1, 2)), ((0, 2), (1, 3)), 
((0, 2), (2, 3)), ((0, 3), (1, 2)), ((0, 3), (1, 3)), ((0, 3), (2, 3)), 
((1, 2), (1, 3)), ((1, 2), (2, 3)), ((1, 3), (2, 3))] 
+0

但是這隻給出了[(0,1),(0,2),(0,3),(1,2),(1,3),(2,3)]',他的問題是一個小問題不同,我認爲 – thefourtheye

+0

這給出了所有不同的配對。我希望所有(不同的)對(不同的)對。但我可以做ll = itertools.combinations(l,2)。在itertools.combinations(ll,2)中配對:謝謝。 – octonots

+0

是的,我發現,抱歉;編輯! – jonrsharpe

相關問題