[Tutor] .sort(key = ???)

Alan Gauld alan.gauld at btinternet.com
Thu Nov 16 23:50:08 CET 2006


"Dave S" <pythontut at pusspaws.net> wrote

> I have a bunch of lists within lists that I need to sort ref item 
> [4], I can't
> access my code at the moment but I basically ...
>
> a = [[...], [...], .... ]
> a.sort(item4)
>
> def item4(a,b):
> return a[4], b[4]
>
>
> Having googled I think there is a better way of doing this with the 
> key
> attribute
>
> a.sort(key= ?? )
>
> I cant get a handle on how key works or how to code it for my needs.

key is a function that returns the sortable item given the list as 
input.
Thus for your example:

a.sort(key=lambda s:s[4])

Or if you don't like lambdas:

def item4(aSeqence): return aSequence[4]
a.sort(key=item4)

You can do some more "interesting" things with key too, including
returning values derived from the original list, but the use shown is
the basic technique.

HTH,

Alan G. 




More information about the Tutor mailing list