Chunking sequential values in a list

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Thu Jul 13 16:31:39 EDT 2006


It looks like homework. Sometimes the simpler code is better:

def splitter(seq):
    if not seq:
        return []
    result = []
    current = [seq[0]]
    for pos, el in enumerate(seq[1:]):
        if el - current[-1] > 1:
            result.append(current[:])
            current = []
        current.append(el)
    result.append(current)
    return result

print splitter([1, 2, 3, 5, 6, 8, 12])
print splitter([1, 1, 1, 2, 2, 5, 6])
print splitter([1, 1, 1, 1, 1, 1, 1])
print splitter([1, 2, 3])
print splitter([1])
print splitter([])
print splitter([1.0, 1.1, 1.99, 4.01])
print splitter([1.0, 2.0, 3.0, 4.01])

To reduce memory used you can use islice instead of the slice seq[1:]
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)]

Bye,
bearophile




More information about the Python-list mailing list