[Tutor] Grouping based on attributes of elements in a List

Rafael Durán Castañeda rafadurancastaneda at gmail.com
Tue Mar 29 23:57:41 CEST 2011


This would work nice too:

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')  ]
>>> sorted(list_,key=lambda l: l[1:3])
[('G1', 'CFS', 'FCL', 'R1'), ('G4', 'CFS', 'FCL', 'R10'), ('G1', 'CFS',
'FCL', 'R2'), ('G2', 'LOOSEFREIGHT', 'LCL', 'R4'), ('G2', 'LOOSEFREIGHT',
'LCL', 'R5'), ('G3', 'LOOSEFREIGHT', 'MIXEDLCL', 'R9')]
>>>

And more pythonic, I think

2011/3/29 Sander Sweers <sander.sweers at gmail.com>

> On 29 March 2011 22:03, ranjan das <ranjand2005 at gmail.com> wrote:
> > 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?
>
> You can use itemgetter from the operator module. The below should do
> what you want. I am using sorted to return a new list but you can also
> sort the list in place with list.sort().
>
> >>> import operator
> >>> l =[( 'G1', 'CFS', 'FCL', 'R1' ),('G3', 'LOOSEFREIGHT', 'MIXEDLCL',
> 'R9'), ('G4', 'CFS', 'FCL', 'R10' ), ('G2',  'LOOSEFREIGHT', 'LCL', 'R4' ),
> ('G1', 'CFS', 'FCL', 'R2' ), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5') ]
> >>> sorted(l, key=operator.itemgetter(1,2))
> [('G1', 'CFS', 'FCL', 'R1'), ('G4', 'CFS', 'FCL', 'R10'), ('G1',
> 'CFS', 'FCL', 'R2'), ('G2', 'LOOSEFREIGHT', 'LCL', 'R4'), ('G2',
> 'LOOSEFREIGHT', 'LCL', 'R5'), ('G3', 'LOOSEFREIGHT', 'MIXEDLCL',
> 'R9')]
>
> Greets
> Sander
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110329/92692070/attachment.html>


More information about the Tutor mailing list