need help on need help on generator...
Francis Girard
francis.girard at free.fr
Fri Jan 21 10:05:38 EST 2005
Hi,
I recently read David Mertz (IBM DeveloperWorks) about generators and got
excited about using lazy constructs in my Python programming.
But besides the fact that generators are either produced with the new "yield"
reserved word or by defining the __new__ method in a class definition, I
don't know much about them.
In particular, I don't know what Python constructs does generate a generator.
I know this is now the case for reading lines in a file or with the new
"iterator" package. But what else ? Does Craig Ringer answer mean that list
comprehensions are lazy ? Where can I find a comprehensive list of all the
lazy constructions built in Python ? (I think that to easily distinguish lazy
from strict constructs is an absolute programmer need -- otherwise you always
end up wondering when is it that code is actually executed like in Haskell).
Thank you
Francis Girard
FRANCE
Le vendredi 21 Janvier 2005 15:38, Craig Ringer a écrit :
> On Fri, 2005-01-21 at 17:14 +0300, Denis S. Otkidach wrote:
> > On 21 Jan 2005 05:58:03 -0800
> >
> > joh12005 at yahoo.fr (Joh) wrote:
> > > i'm trying to understand how i could build following consecutive sets
> > > from a root one using generator :
> > >
> > > l = [1,2,3,4]
> > >
> > > would like to produce :
> > >
> > > [1,2], [2,3], [3,4], [1,2,3], [2,3,4]
> > >
> > >>> def consecutive_sets(l):
> >
> > ... for i in xrange(2, len(l)):
> > ... for j in xrange(0, len(l)-i+1):
> > ... yield l[j:j+i]
>
> Since you have a much faster brain than I (though I ended up with
> exactly the same thing barring variable names) and beat me to posting
> the answer, I'll post the inevitable awful generator expression version
> instead:
>
> consecutive_sets = ( x[offset:offset+subset_size]
> for subset_size in xrange(2, len(x))
> for offset in xrange(0, len(x) + 1 - subset_size) )
>
> --
> Craig Ringer
More information about the Python-list
mailing list