slice iterator?

Ned Deily nad at acm.org
Sat May 9 00:14:32 EDT 2009


In article <7xprejoswg.fsf at ruckus.brouhaha.com>,
 Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote:
> Ross <ross.jett 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,
 nad at acm.org




More information about the Python-list mailing list