Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested generator to nested list

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.

like image 278
user8493571 Avatar asked Aug 03 '26 03:08

user8493571


1 Answers

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]]
like image 143
Ch3steR Avatar answered Aug 05 '26 15:08

Ch3steR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!