A way to re-organize a list

Gordon Airporte JHoover at fbi.gov
Thu Jul 19 21:05:46 CEST 2007


beginner wrote:
> 
> What I want to do is to reorganize it in groups, first by the middle
> element of the tuple, and then by the first element. I'd like the
> output look like this:

itertools.groupby has already been mentioned, but it has a very specific 
and complex behavior which may not be exactly what you need. I found 
this handy class:

class groupby(dict):
     def __init__(self, seq, key=lambda x:x):
         for value in seq:
             k = key(value)
             self.setdefault(k, []).append(value)
     __iter__ = dict.iteritems

which you would use like this:

byfirst = groupby(l, lambda x: x[0])
print byfirst['A']
print byfirst['B']
bysecond = groupby(l, lambda x: x[1])
print bysecond['a']
print bysecond['b']




More information about the Python-list mailing list