Transforming a List of elements into a List of lists of elements
jeanmichel at sequans.com
Fri Jan 8 13:39:05 CET 2010
tiago almeida 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.
> print( f(a, 2) ) # -> [ [1, 2], [3, 4],  ]
> print( f(a, 3) ) # -> [ [1, 2, 3], [4, 5] ]
> print( f(a, 1) ) # -> [ , , , ,  ]
> 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?
> Ps: I don't post the function here because I don't have it with me.
> Thanks a lot in advance!
> Tiago Almeida
> tiago.b.almeida at gmail.com <mailto:tiago.b.almeida at gmail.com>
using list comprehention
# note: poor naming
def func(l, slice):
r = range(0, len(l), slice)
result = [l[sl:sl+slice] for sl in r]
>>> func(a,1) ; func(a,2) ; func(a,3)
[, , , , ]
[[1, 2], [3, 4], ]
[[1, 2, 3], [4, 5]]
I would add that I personally find list comprehension hard to read, so
I'm not sure it is that pythonic. Your old school while loop could be
less concise/elegant, but perfectly readable.
More information about the Python-list