Python - Generator Within Another Generator
I have to use the output of a generator in another generator. Below is the code - Here Generator 2 is called within generator 1 and the final output is received from generator 2.
Solution 1:
I'm pretty sure the only issue in your short sub_gen
generator is that you've written yield each
instead of yield from
. The latter expects an iterable value after it (often another generator), and it yields each value just like an explicit for loop
So I think your code should be:
defsub_gen(data) :
for r in res_gen() :
yieldfrom train_datagen(r)
Lets test this with much simpler generator functions:
def foo():
yield [1, 2]
yield [3, 4]
def bar(iterable):
for x in iterable:
yield10+x
yield20+x
def baz():
foriterable in foo():
yieldfrom bar(iterable)
for value in baz(): # use the top-level generator!print(value) # prints 11, 21, 12, 22, 13, 23, 14, 24 each on its own line
Post a Comment for "Python - Generator Within Another Generator"