Grouping lists

P

PyPK

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,
 
A

aurora00

I wasn't sure of what itertools.groupby() is good for. But it serves
your purpose.
lst = [1,1,1,1,3,5,1,1,1,1,7,7,7]

import itertools
i = 0
groups = []
for k, g in itertools.groupby(lst):
.... l = len(list(g))
.... if l == 1:
.... groups.append(i)
.... else:
.... groups.append((i, i+l-1))
.... i += l
....[(0, 3), 4, 5, (6, 9), (10, 12)]
 
P

PyPK

hmm thanks for that..but kind of not sure how this groupby works.. also
if I want to group elements with one value apart how would this
change.Should this change in groupby part or in the loop?
something like...
lst = [1,1,2,1,3,5,1,1,1,1,2,7,7]
returns (0,3),4,5,(6,10),(11,12)
so its something like if there is 1,1,2 then the grouping is done..
I am asking this as I could not quit follow what exactly groupby does..

Also if someone could explain me what exactly this groupby is doing
that would be helpful.

Thanks again.
 
K

Kay Schluehr

PyPK said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,264
Messages
2,571,315
Members
48,001
Latest member
Wesley9486

Latest Threads

Top