Python:获取itertools.combinations以逐步返回更大的组合

时间:2017-03-26 22:29:43

标签: python python-2.7 combinatorics 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], 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
...

1 个答案:

答案 0 :(得分:2)

摆脱response.code()

[: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)