Grouping lists

Kay Schluehr kay.schluehr at gmx.net
Mon Sep 12 19:17:15 CEST 2005


PyPK wrote:
> If I have a list say
>
> lst = [1,1,1,1,3,5,1,1,1,1,7,7,7]
> I want to group the list so that it returns groups such as
> [(0,3),4,5,(6,9),(10,12)]. which defines the regions which are similar.
>
> Thanks,

Hi,

I got a solution without iterators and without comparing adjecent
elements! O.K. it is neither the most efficient nor the most obvious
solution but I didn't want to get bored ;)

import sets

l = [1,1,8,1,1,3,5,1,1,1,1,7,7,7]
regions = []

for x in sets.Set(l):
    start = l.index(x,0)
    cnt = 0
    while 1:
        try:
            idx = l.index(x,start)
            if idx!=start:
                regions.append((start-cnt,start-1))
                cnt   = 0
                start = idx
            else:
                cnt+=1
                start+=1
        except ValueError:
            regions.append((start-cnt,start-1))
            break

regions.sort()

This returns [(0, 3), (4, 4), (5, 5), (6, 9), (10, 12)]

Now splitting l in regions:

>>> [l[i:j+1] for (i,j) in regions]
[[1, 1, 1, 1], [3], [5], [1, 1, 1, 1], [7, 7, 7]] 

Kay




More information about the Python-list mailing list