2017-03-26 49 views
1

現在我使用:的Python:獲得itertools.combinations返回逐漸變大的組合

list_one = ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10)) 
list_two = [] 
print "List One: " + str(list_one) 
for i in range(0, 5): 
     list_two = tuple(c for i in range(len(list_one)) 
          for c in itertools.combinations(list_one[:i], i)) 
print "List Two: " + str(list_two) 

,輸出:

List One: ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10)) 
List Two: ((), ((1, 2),), ((1, 2), (3, 4)), ((1, 2), (3, 4), (5, 6)), ((1, 2), (3, 4), (5, 6), (7, 8))) 

我要的是:

List One: ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10)) 
List Two: ((), ((1, 2),), ((3, 4),), ((5, 6),), ((7, 8),), ((9, 10),), ((1, 2), (3, 4)), ((1, 2), (5, 6)), ((1, 2), (7, 8)), ((1, 2), (9, 10)), ((3, 4), (5, 6)), ((3, 4), (7, 8)) ... 

所以第一輪將是單項物品
第二階段包括所有2項組合,包括(1,2),等等
第三關包括所有3項的組合,包括(1,2)和(3,4),等等

的簡化版本:

list_one = ((1), (2), (3), (4), (5)) 

將輸出:

((1), (2), (3), (4), (5), ((1), (2)), ((1), (3)), ((1), (4)), ((1), (5)), ((2), (3)), ((2), (4))... ((3), (4), (5))) 

如何修改以使得它從移動:
1 - > 2 - > 3 - > 4 - > 5
1,2 - > 1,3 - > 1,4 - > 1,5
...

+0

......我硬編碼的我想要的輸出,因此如果在組合中的缺陷,讓我知道。 – user58446

回答

1

剛剛擺脫的[:i]

import itertools 

list_one = ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10)) 
list_two = [] 
print "List One: " + str(list_one) 
for i in range(0, 5): 
    list_two = tuple(c for i in range(len(list_one)) 
        for c in itertools.combinations(list_one, i)) 
print "List Two: " + str(list_two) 

輸出:

List One: ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10)) 
List Two: ((), ((1, 2),), ((3, 4),), ((5, 6),), ((7, 8),), ((9, 10),), ((1, 2), (3, 4)), ((1, 2), (5, 6)), ((1, 2), (7, 8)), ((1, 2), (9, 10)), ((3, 4), (5, 6)), ((3, 4), (7, 8)), ((3, 4), (9, 10)), ((5, 6), (7, 8)), ((5, 6), (9, 10)), ((7, 8), (9, 10)), ((1, 2), (3, 4), (5, 6)), ((1, 2), (3, 4), (7, 8)), ((1, 2), (3, 4), (9, 10)), ((1, 2), (5, 6), (7, 8)), ((1, 2), (5, 6), (9, 10)), ((1, 2), (7, 8), (9, 10)), ((3, 4), (5, 6), (7, 8)), ((3, 4), (5, 6), (9, 10)), ((3, 4), (7, 8), (9, 10)), ((5, 6), (7, 8), (9, 10)), ((1, 2), (3, 4), (5, 6), (7, 8)), ((1, 2), (3, 4), (5, 6), (9, 10)), ((1, 2), (3, 4), (7, 8), (9, 10)), ((1, 2), (5, 6), (7, 8), (9, 10)), ((3, 4), (5, 6), (7, 8), (9, 10))) 
+0

只是想出了。如果這個問題沒有被提出或回答,我會刪除它。但你仍然會得到你的答案:)謝謝。 – user58446