Chunking sequential values in a list

skip at pobox.com skip at pobox.com
Fri Jul 14 00:49:30 EDT 2006


    Gerard> David Hirschfield wrote:
    >> I have this function:
    >> 
    >> def sequentialChunks(l, stride=1):
    ...
    >> 
    >> Which takes a list of numerical values "l" and splits it into chunks
    >> where each chunk is sequential...

    Gerard> see the groupby example here:

    Gerard> http://docs.python.org/lib/itertools-example.html 

I've never been a fan of the operator module, so I find the example in the
docs ugly even though it's succinct.  I'd also never used groupby but
thought it was the solution to the problem.  As I was walking home from the
train I realized how it would work.  You beat me to the punch with your
reply, but I'll post my solution anyway:

    from itertools import groupby

    class Counter:
        def __init__(self):
            self.last = None
            self.value = True

        def __call__(self, val):
            if self.last is not None and self.last+1 != val:
                self.value = not self.value
            self.last = val
            return self.value

    for key, group in groupby([1,2,3, 5,6, 8, 12,13,14], Counter()):
        print list(group)

Skip



More information about the Python-list mailing list