Transforming a List of elements into a List of lists of elements

Jan Kaliszewski zuo at chopin.edu.pl
Fri Jan 8 07:16:34 EST 2010


08-01-2010 tiago almeida <tiago.b.almeida at gmail.com> wrote:

> Hello all,
>
> I'd like to ask how you'd implement a function *f* that transforms a  
> list of elements into a list of lists of elements by grouping
> contiguous elements together.
> Examples:
>
> a=[1,2,3,4,5]
> print( f(a, 2) )   # -> [ [1, 2], [3, 4], [5] ]
> print( f(a, 3) )   # -> [ [1, 2, 3], [4, 5] ]
> print( f(a, 1) )   # -> [ [1], [2], [3], [4], [5] ]
>
>
> I have done a small function that does this using a while loop but
> what I'm looking for is a more *pythonic* way to do this. Maybe
> some function in some standard Module does this and I don't know?

[In Python 2.x]

     >>> s = [1,2,3,4,5]
     >>> zip(*[iter(s)]*3)  # zip truncates result
     [(1, 2, 3)]
     >>> zip(*[iter(s)]*2)
     [(1, 2), (3, 4)]
     >>> zip(*[iter(s)]*3)  # or simpler: zip(s) :-)
     [(1,), (2,), (3,), (4,), (5,)]
     >>> map(None, *[iter(s)]*2)  # map fills result with None
     [(1, 2), (3, 4), (5, None)]
     >>> map(None, *[iter(s)]*3)
     [(1, 2, 3), (4, 5, None)]

Instead of map, you can use izip_longest from itertools module:

     >>> list(itertools.izip_longest(*[iter(s)]*3))
     [(1, 2, 3), (4, 5, None)]
     >>> list(itertools.izip_longest(*[iter(s)]*2))
     [(1, 2), (3, 4), (5, None)]

See:
http://docs.python.org/library/functions.html#zip
http://docs.python.org/library/functions.html#map
http://docs.python.org/library/itertools.html#itertools.izip_longest

Cheers,
*j

-- 
Jan Kaliszewski (zuo) <zuo at chopin.edu.pl>



More information about the Python-list mailing list