简体   繁体   中英

Printing a generator object in Python

I'm trying to have access to all elements created by a generator, as per the following code:

from itertools import combinations


Fatores = ['Ft', 'Fp', 'Floc']


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)

panel = combinations(Fatores,2)
for subset in panel:
    print(subset)

However, I'm having the following error message:

TypeError: 'range' object does not support item assignment

Does anybody have some hint to solve this problem?

Kind Regards

Something wrong is with your code

1.

if r > n: return indices = range(r) yield tuple(pool[i] for i in indices) indices assignment should be above return and than return should return just variable

  1. yield is used in for loop which is not in your example

i'm not pretty sure what this part try to do but i think above if should be for loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM