简体   繁体   中英

Looping through a generator that returns multiple values

My generator ( batch_generator ) returns 5 values, but I can't seem to figure out how to loop through the values.

Things I've tried:

1) Unpack directly in the for loop definition ( ValueError: too many values to unpack (expected 5) )

for a, b, c, d, e in next(batch_generator):
    # do something with a-e

2) Unpack within the for loop ( ValueError: too many values to unpack (expected 5) on the line where I unpack item )

for item in next(batch_generator):
    a, b, c, d, e = item
    # do stuff

3) Zip it and unpack in the for loop definition ( ValueError: not enough values to unpack (expected 5, got 1) )

for a, b, c, d, e in zip(next(batch_generator)):
    # do stuff

4) Zip it and unpack within the for loop ( ValueError: not enough values to unpack (expected 5, got 1) on the line where I unpack item , I think it's just wrapped in another tuple now)

for item in zip(next(batch_generator)):
     a, b, c, d, e = item

Any explanation of what's really going on with the tuples/generator would be appreciated!

My yield statement looks like yield a, b, c, d, e

Based on that comment, the generator seems to emit a sequence of 5-tuples.

You can then simply use:

for a, b, c, d, e in batch_generator:
    #                ^ no next(..)
    pass

So you should not use next(..) . Next simply returns the next yield . Now since that is a tuple, the for loop will iterate over the tuple , instead of the generator.

The for loop will iterate over the tuples the generator batch_generator emits, until the generator is exhausted (or there is a break / return statement in the for loop that is activated.

Mind that a for loop works like:

for <pattern> in <expression>:
    # ...

The <expression> should be an iterable (generator, tuple, list,...) and the <pattern> is used to assign to. If you iterate over the tuple, you thus iterate over the elements of that tuple, not the tuple in full.

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