Sorting a multidimensional array by multiple keys

Alex Martelli aleax at mac.com
Mon Apr 2 01:07:52 EDT 2007


Thomas Krüger <newsgroups at nospam.nowire.org> wrote:

> Rehceb Rotkiv schrieb:
> > can I sort a multidimensional array in Python by multiple sort keys? A
> > litte code sample would be nice!
> 
> You can pass a function as argument to the sort method of a list.
> The function should take two arguments and return -1, 0 or 1 as
> comparison result. Just like the cmp function.
> 
> This will objects in list obj_lst by their id attributes:
> 
> def sorter(a, b):
>     return cmp(a.id, b.id)
> 
> obj_lst.sort(sorter)

A MUCH better way to obtain exactly the same semantics would be:

def getid(a):
    return a.id

obj_list.sort(key=getid)


Alex



More information about the Python-list mailing list