Sorting a list by another's order

Mark McEahern marklists at mceahern.com
Fri Aug 30 16:22:12 CEST 2002


[Graeme Longman]
> Would it be much trickier if the list that needs sorting is a
> list of tuples
> and I need to sort it by the first item of each tuple ?

You'd just need to tweak the function that does the sorting.  Notice I'm
using the list's built-in sort function:

$ python
Python 2.2.1 (#1, Jun 25 2002, 10:55:46)
[GCC 2.95.3-5 (cygwin special)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> list.sort.__doc__
'L.sort([cmpfunc]) -- sort *IN PLACE*; if given, cmpfunc(x, y) -> -1, 0, 1'

So a basic function for tuples would look like this:

def sort_tuples(x, y):
    return cmp(x[0], y[0])

You then just need to modify make_sort_by_list() to return a more complex
version of this (accounting for elements that aren't in the sort list) with
the sort list in the nested scope.

Cheers,

// mark

-





More information about the Python-list mailing list