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

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

最佳答案

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

相关文章:

python - Python 中的排序-合并-连接算法

python - 如何填充表格中缺失的元素?

python - yield 在 python 2.7 中有什么作用?

python - 在 Python 中将大数与小数相加

python - 忽略 python 中的 IPython 魔法

python - 填充轮廓 OpenCV 的外部

python - 如何根据传递到 __init__ 方法的字符串值来命名类内的变量?

r - 如何使用 R 中的递归创建长度为 n 的所有 2^n 二进制序列的矩阵?

python - 生成元素之和固定的非负整数数组

python - 列表字典的笛卡尔积