Secondary list sorting comparison expression

Raymond Hettinger vze4rx4y at verizon.net
Tue Mar 8 14:46:15 EST 2005


[David Pratt]
> I am wanting to
> extend this with a better comparison expression so that it would sort
> on one key as primary, a second key as secondary sort , and maybe even
> a third as tertiary.

The simplest approach is to rely on Python's sort being stable.  First sort on
the tertiary key, then do another sort on the secondary key, and then sort on
the primary key.


> def sort_by_key(list, i):
>        list.sort(lambda a, b: cmp(a[i], b[i]))

Another way is to build out the sort_by_key function to handle multiple fields:

def sort_by_key(list, i, j, k):
       list.sort(lambda a, b: cmp((a[i], a[j], a[k]), (b[i], b[j], b[k])))

In Py2.4, the key= option offers an alternative to cmp which is simpler and
faster:

def sort_by_key(list, i, j, k):
       list.sort(key = lambda a : (a[i], a[j], a[k]))


Raymond Hettinger





More information about the Python-list mailing list