slice iterator?

Paul McGuire ptmcg at austin.rr.com
Sat May 9 01:04:33 EDT 2009


On May 8, 11:14 pm, Ned Deily <n... at acm.org> wrote:
> In article <7xprejoswg.... at ruckus.brouhaha.com>,
>  Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
>
>
>
>
>
> > Ross <ross.j... at gmail.com> writes:
> > > I have a really long list that I would like segmented into smaller
> > > lists. Let's say I had a list a = [1,2,3,4,5,6,7,8,9,10,11,12] and I
> > > wanted to split it into groups of 2 or groups of 3 or 4, etc. Is there
> > > a way to do this without explicitly defining new lists?
>
> > That question comes up so often it should probably be a standard
> > library function.
>
> > Anyway, here is an iterator, if that's what you want:
> >    >>> from itertools import islice
> >    >>> a = range(12)
> >    >>> xs = iter(lambda x=iter(a): list(islice(x,3)), [])
> >    >>> print list(xs)
> >    [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
> > Of course, as the saying goes, there's more than one way to do it ;-)
>
> python2.6 itertools introduces the izip_longest function and the grouper
> recipe <http://docs.python.org/library/itertools.html>:
>
> def grouper(n, iterable, fillvalue=None):
>     "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
>     args = [iter(iterable)] * n
>     return izip_longest(fillvalue=fillvalue, *args)
>
> --
>  Ned Deily,
>  n... at acm.org- Hide quoted text -
>
> - Show quoted text -

Here's a version that works pre-2.6:

>>> grouper = lambda iterable,size,fill=None : zip(*[(iterable+[fill,]*(size-1))[i::size] for i in range(size)])
>>> a = range(12)
>>> grouper(a,6)
[(0, 1, 2, 3, 4, 5), (6, 7, 8, 9, 10, 11)]
>>> grouper(a,5)
[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9), (10, 11, None, None, None)]
>>> grouper(a,3)
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]

-- Paul



More information about the Python-list mailing list