Python:获取 itertools.combinations 以返回逐渐变大的组合
Posted
技术标签:
【中文标题】Python:获取 itertools.combinations 以返回逐渐变大的组合【英文标题】:Python: get itertools.combinations to return progressively larger combinations 【发布时间】:2017-03-26 22:29:43 【问题描述】:我现在正在使用:
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】:干掉[: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 以返回逐渐变大的组合的主要内容,如果未能解决你的问题,请参考以下文章