what are generators?
castironpi at gmail.com
castironpi at gmail.com
Thu Mar 27 07:19:18 EDT 2008
On Mar 25, 7:36 pm, Miki <miki.teb... at gmail.com> wrote:
> On Mar 24, 8:17 am, castiro... at gmail.com wrote:
>
> > I'm looking for a cool trick using generators. Know any exercises I
> > can work?
>
> Simple one the comes to mind is flattening a list:
>
> >>> list(flatten([1, [[2], 3], [[[4]]]]))
> [1, 2, 3, 4]
I don't think it's well-defined. (But this is impossible and useless
calling.) CMIIW?
This is generic:
>>> def f():
... __gen= None
... def g():
... i= 0
... while 1:
... i+= 1
... yield __gen( i )
... def set( gen ):
... nonlocal __gen
... __gen= gen
... return g, set
...
>>> a, set= f()
>>> b= a()
>>> set( lambda x: print( x ) )
>>> next( b )
1
>>> next( b )
2
>>> next( b )
More information about the Python-list
mailing list