[Tutor] sorting lists into sub lists based on a key
Iyer
maseriyer at yahoo.com
Thu Jun 21 02:22:50 CEST 2007
if I have a list of lists, that goes like this: [[0,['a','b']],[0,['c','d']],[3,['f','g']], [0,['a','b']],[0,['c','d']], [3,['f1','f2']], [2,['zz','dd']]]
what could be the best way to reorder this such that the sublists with the same first element go into their own sub-list ?
like,
sublist0 = [0,['a','b']],[0,['c','d']],[0,['a','b']],[0,['c','d']]
sublist2 = [2,['zz','dd']]
sublist3 [3,['f','g']], [3,['f1','f2']]
Does this seem to be the best way to do it ?
===============================================================================
from operator import itemgetter
from itertools import groupby
data_list = [[0,['a','b']],[0,['c','d']],[3,['f','g']], [0,['a','b']],[0,['c','d']], [3,['f1','f2']], [2,['zz','dd']]]
data_list.sort()
list1 = []
for key, items in groupby(data_list, key= itemgetter(0)):
list1.append(list(items))
print "After grouping the list by first value in each element:"
print list1
print "printing each sublist"
for i in list1:
print i
===============================================================================
output :
After grouping the list by first value in each element:After grouping the list by first value in each element:
[[[0, ['a', 'b']], [0, ['a', 'b']], [0, ['c', 'd']], [0, ['c', 'd']]], [[2, ['zz', 'dd']]], [[3, ['f', 'g']], [3, ['f1', 'f2']]]]
printing each sublist
[[0, ['a', 'b']], [0, ['a', 'b']], [0, ['c', 'd']], [0, ['c', 'd']]]
[[2, ['zz', 'dd']]]
[[3, ['f', 'g']], [3, ['f1', 'f2']]]
---------------------------------
Got a little couch potato?
Check out fun summer activities for kids.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070620/dc2fb6ab/attachment.htm
More information about the Tutor
mailing list