iterator question

dannycolligan at gmail.com dannycolligan at gmail.com
Wed Sep 27 09:52:21 EDT 2006


Er, whoops.  That would work if the last item in the list was 10 (and,
of course, this doesn't work for any arbitrary sequence).  Is there any
"look-ahead" function for list comprehensions?

Danny

dannycolligan at gmail.com wrote:
> Simple list comprehension?
>
> >>> l = [1,2,3,4,5,6,7,8,9,0]
> >>> [(x, x+1) for x in l if x%2 == 1]
> [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
>
> Danny
>
> Neal Becker wrote:
> > George Sakkis wrote:
> >
> > > johnzenger at gmail.com wrote:
> > >
> > >> def transform(seq, size):
> > >>     i = 0
> > >>     while i < len(seq):
> > >>         yield tuple(seq[i:i+size])
> > >>         i += size
> > >
> > > Or for arbitrary iterables, not just sequences:
> > >
> > > from itertools import islice
> > > def transform(iterable, size):
> > >      it = iter(iterable)
> > >      while True:
> > >          window = tuple(islice(it,size))
> > >          if not window:
> > > break
> > >          yield window
> > >
> > > George
> > >
> > 
> > Thanks guys!
> > 
> > This one above is my personal favorite.




More information about the Python-list mailing list