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 (Va
Solution 1:
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.
Post a Comment for "Looping Through A Generator That Returns Multiple Values"