444,050 Members | 1,020 Online
Need help? Post your question and get tips & solutions from a community of 444,050 IT Pros & Developers. It's quick & easy.

# Grouping lists

 P: n/a 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, Sep 9 '05 #1
4 Replies

 P: n/a 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 .... groups [(0, 3), 4, 5, (6, 9), (10, 12)] Sep 9 '05 #2

 P: n/a PyPK wrote: 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. You'll probably want to use "groupby" from the itertools module. See http://docs.python.org/lib/itertools-functions.html -- Benji York Sep 9 '05 #3

 P: n/a 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. Sep 12 '05 #4

 P: n/a 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 Sep 12 '05 #5

### This discussion thread is closed

Replies have been disabled for this discussion.