Chunking sequential values in a list

Gerard Flanagan grflanagan at yahoo.co.uk
Fri Jul 14 07:17:26 EDT 2006


skip at pobox.com wrote:
> 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)
>

I've no strong feelings about the operator module myself, or the
groupby example, but I do prefer your code in this case.  I tweaked it
a little to take into account the stride, though I'm not sure it gives
what the OP wants.

all the best

Gerard

-----------------------------

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

    def __call__(self, val):
        if self.last is not None:
            d = val - self.last
            if d > self.stride:
                self.value = not self.value
        self.last = val
        return self.value

def group(data,stride=1):
    for key, group in groupby(data, Counter(stride)):
        yield list(group)

-----------------------------------




More information about the Python-list mailing list