I sometimes end up in a situation where I'm working with a generator whose members are themselves generators (and so on for n levels).
When debugging, printing these results in the useless <generator object blah at blah>
Obviously I can do print(list(my_gen)) to convert the top level to a list. But then I get
[<generator object blah at blah>, <generator object blah at blah>, <generator object blah at blah>]
which is equally useless.
Is there a simple command for printing a nested generator evaluated all the way down?
I know that I could write a recursive function to do this, but I'm looking for a simple method.
You can write a recursive function to evaluate N-level nested generator. I don't think a built-in function exists for this.
import types
def _gen(gen):
if not isinstance(gen,types.GeneratorType):
return gen
else:
return [_gen(i) for i in gen]
my_gen=((j for j in range(i)) for i in range(10))
print(_gen(my_gen))
[[],
[0],
[0, 1],
[0, 1, 2],
[0, 1, 2, 3],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4, 5],
[0, 1, 2, 3, 4, 5, 6],
[0, 1, 2, 3, 4, 5, 6, 7],
[0, 1, 2, 3, 4, 5, 6, 7, 8]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With