【问题标题】:Having trouble printing combinations generator打印组合生成器时遇到问题
【发布时间】:2017-03-20 22:57:48
【问题描述】:

所以我正在探索 itertools.combinations 背后的代码。在文档中,它给出了“等效”,如下所示:

def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = range(r)
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

假设我有一个列表:

sequence = [1,2,3,4,5,6,7,8,9,10] 

和:

r=3

我尝试将生成器转换为列表,然后打印它,但我得到了:

print(list(combinations(sequence,3)))
...
---> 16         indices[i] += 1
 17         for j in range(i+1, r):
 18             indices[j] = indices[j-1] + 1
TypeError: 'range' object does not support item assignment

我无法修改它以使其正常工作而不会导致更多错误。 如果有人可以为我提供一些关于如何解决此 TypeError 的指导,我将不胜感激。

简而言之,我想知道为什么这样做可行,但之前的代码却不行:

print(list(itertools.combinations(sequence,3)))
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 2, 6), (1, 2, 7) ...]

【问题讨论】:

标签: python python-3.x


【解决方案1】:

通过修改行:

indices = range(r)

到:

indices = list(range(r))

回答了我的问题。谢谢cmets。

【讨论】:

    猜你喜欢
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2021-10-13
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多