Break up list into groups

marduk marduk at nbk.hopto.org
Mon Jul 16 23:31:19 CEST 2007


On Mon, 2007-07-16 at 14:11 -0700, danmcleran at yahoo.com wrote:
> I can't seem to find an answer to this question anywhere, but I'm
> still looking. My problem is I have a list of values like this:
> 
> l = [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, 12,
> 13, 0xF0, 14, 0xF1, 15]
> 
> A value with bit 0x80 set delineates the start of a new packet of
> information. What I want to do is to group the packets so that 1, 2, 3
> go with the 1st packet tagged 0xF0, 4 ,5, 6 go with the 2nd packet
> tagged 0xF0, 7 & 8 go with the packet tagged 0xF1 and so on. The
> length of the data associated with each tag can vary. I've already
> written an algorithm to do this but I was wondering if some
> combination of itertools functions could do the job faster?
> 
> Here's what I've done and the expected output of the algorithm:
> 
> def splitIntoGroups(data):
>     groups = []
>     local = []
> 
>     for value in data:
>         if 0x80 & value:
>             if len(local) > 0:
>                 groups.append(local)
> 
>             local = []
>             local.append(value)
>         else:
>             local.append(value)
> 
>     if len(local) > 0:
>         groups.append(local)
> 
>     return groups
> 
> l = [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, 12,
> 13, 0xF0, 14, 0xF1, 15]
> 
> print splitIntoGroups(l)
> 
> Desired result:
> 
> [[240, 1, 2, 3], [240, 4, 5, 6], [241, 7, 8], [242, 9, 10, 11, 12,
> 13], [240, 14], [241, 15]] 

Assuming you meant '0xF0' instead of '0x80'.... do you mean any value
>=240 starts a new group?  If so:

groups = []
current = [] # probably not necessary, but as a safety
for i in l:
    if i >= 240:
        current = []
        groups.append(current)
    current.append(i)





More information about the Python-list mailing list