what are generators?

castironpi at gmail.com castironpi at gmail.com
Thu Mar 27 07:45:40 EDT 2008


On Mar 27, 6:19 am, castiro... at gmail.com wrote:
> 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:

Revise:

>>> def f():
...     __gen= None
...     def set( gen ):
...             nonlocal __gen
...             __gen= gen
...     yield set
...     i= 0
...     while 1:
...             i+= 1
...             yield __gen( i )
...
>>> a= f()
>>> set= next( a )
>>> set( lambda x: print( x ) )
>>> next( a )
1
>>> next( a )
2
>>> next( a )
3
>>>



More information about the Python-list mailing list