[Tutor] Grouping based on attributes of elements in a List
eli.nazarova at gmail.com
Tue Mar 29 22:28:04 CEST 2011
On 3/29/2011 4:03 PM, 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  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 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 
> however I was not able to further divide them based on index 
> Any help is appreciated
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
You can you list comprehension (three times) checking for membership of
the relevant items, or you can use for loop to go over all available
tuples and sort them into different lists using if. In any case, after
that you create a list of the three required lists.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor