Break up list into groups

Miki miki.tebeka at gmail.com
Wed Jul 18 16:51:05 CEST 2007


Hello Dan,

Yet another option (using itertools.groupby):

from itertools import groupby

class GrouperToggler:
    def __init__(self):
        self.group = 1

    def __call__(self, value):
        # New packet, toggle group
        if value & 0x80:
            self.group = 1 - self.group
        return self.group

def group(items):
    for group, items in groupby(items, GrouperToggler()):
        # groupby return [key, group_iterator]
        yield [item for item in items]

i = [
    0xF0, 1, 2, 3,
    0xF0, 4, 5, 6,
    0xF1, 7, 8,
    0xF2, 9, 10, 11, 12, 13,
    0xF0, 14,
    0xF1, 15
]

for g in group(i):
    print g

HTH,
--
Miki <miki.tebeka at gmail.com>
http://pythonwise.blogspot.com




More information about the Python-list mailing list