minor generator question

Denis S. Otkidach ods at fep.ru
Fri Apr 19 13:09:49 EDT 2002


On Fri, 19 Apr 2002, holger krekel wrote:

hk> i have a recursive generator to flatten
hk> nested containers (lists and tuples):
hk>
hk> def flatten(*args):
hk>     for arg in args:
hk>             try:
hk>                 for i in arg:
hk> -->                 for l in flatten(i):
hk> -->                     yield l
hk>
hk>             except TypeError,e: yield arg
hk>
hk>
hk> Is there a better way to say that i want all results
hk> generated from a (sub-)generator be "forwarded" ?
hk> (see the two marked lines).

Related question: why we can write

[j for i in seq for j in func(i)]

but cannot

for i in seq for j in func(i):
    ...


If you don't like deep stair there is solution:

for j in [j for i in seq for j in func(i)]:
    ...

It looks a bit strange...






More information about the Python-list mailing list