[Tutor] Grouping based on attributes of elements in a List
Peter Otten
__peter__ at web.de
Wed Mar 30 09:35:43 CEST 2011
ranjan das wrote:
> I have the following list
>
> List=[( 'G1', 'CFS', 'FCL', 'R1' ),('G3', 'LOOSEFREIGHT', 'MIXEDLCL',
> 'R9'),
> ('G4', 'CFS', 'FCL', 'R10' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R4' ),
> ('G1',
> 'CFS', 'FCL', 'R2' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5') ]
>
>
> now I want to group this elements of List first by index [1] that is (CFS
> and LOOSEFREIGHT ) together and for those elements which are grouped
> together for LOOSEFREIGHT, i want to further divide them into different
> groups based on index[2] that is (LCL or MIXEDLCL)
>
>
> So essentially i want them grouped into different lists and my solution
> should be of the form
>
> New_List=[ [ ( 'G1', 'CFS', 'FCL', 'R1' ), ('G1', 'CFS', 'FCL', 'R2' ),
> ('G4', 'CFS', 'FCL', 'R10' ) ], [ ('G2', 'LOOSEFREIGHT', 'LCL', 'R4' ),
> ('G2', 'LOOSEFREIGHT', 'LCL', 'R5' )], [ ('G3', 'LOOSEFREIGHT',
> 'MIXEDLCL', 'R9')] ]
>
> How do I do it?
>
> I managed to do divide them into different lists based on index [1]
> however
> I was not able to further divide them based on index [2]
>
> Any help is appreciated
Assuming you have a function
def group_list(items, key):
# ...
that takes a list and a function to extract the key you can apply that
recursively first on the initial list, then on all partial lists
def group_recursive(items, keys):
if not keys:
return items
firstkey = keys[0]
rest = keys[1:]
items = group_list(items, firstkey)
if rest:
return [group_recursive(item, rest) for item in items]
return items
if __name__ == "__main__":
from operator import itemgetter
import json
items = [
('G1', 'CFS', 'FCL', 'R1'),
('G3', 'LOOSEFREIGHT', 'MIXEDLCL', 'R9'),
('G4', 'CFS', 'FCL', 'R10'),
('G2', 'LOOSEFREIGHT', 'LCL', 'R4'),
('G1', 'CFS', 'FCL', 'R2' ),
('G2', 'LOOSEFREIGHT', 'LCL', 'R5')
]
groups = group_recursive(items, [itemgetter(1), itemgetter(2)])
print json.dumps(groups, indent=2)
One way to implement group_list() is to sort the items and then use
itertools.groupby() to create the sublists. Another is to put the items into
a dictionary with key(item) as the dict key and a list of items as the
value.
More information about the Tutor
mailing list