gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:09:12 24 4
gpt4 key购买 nike

现在我正在使用:

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
...

最佳答案

只需删除[: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)))

关于Python:获取 itertools.combinations 返回逐渐更大的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43035360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com