Sorting a list by another's order
marklists at mceahern.com
Fri Aug 30 10:22:12 EDT 2002
> 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 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.
'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, y)
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.
More information about the Python-list