Chunking sequential values in a list

Peter Otten __peter__ at web.de
Fri Jul 14 08:06:59 EDT 2006


bearophileHUGS at lycos.com wrote:

> If you want something less easy to understand, you can try fixing the
> following code that doesn't work:
> 
> from itertools import groupby
> l = [1,2,3,5,6,8,12]
> keyf = lambda (pos,x): x-l[pos]>1
> [[el[1] for el in gr] for he,gr in groupby(enumerate(l[:-1]), keyf)]

>>> from itertools import groupby
>>> items = [1, 2, 3, 5, 6, 8, 12]
>>> [[v for i, v in group] for key, group in groupby(enumerate(items),
lambda (i, v): i-v)]
[[1, 2, 3], [5, 6], [8], [12]]

which is almost identical to the last example in 
http://docs.python.org/lib/itertools-example.html

Peter



More information about the Python-list mailing list