[Tutor] Re: sorting nested tuples

Alfred Milgrom fredm at smartypantsco.com
Sat Oct 18 03:45:00 EDT 2003


Hi Conrad:

 >> if I have a list
 >> x = [('hello', 2), ('goodbye', 3), ('python', 1)]
 >> how would i sort it by the 2 variable or any variable for that matter.

Danny has shown one way to sort the list using [decorate-sort-undecorate].
Here is another way to sort your list, by specifying your own compare 
function for sort.

For example:
 >>> def compare(a,b):
         if a[1]>b[1]: return 0
         else: return -1

The function 'compare' we have defined will compare tuples based on the 
second element, returning 0 if true. (Note you could use '>=' depending on 
how you want the compare to operate).

This function is OK for quick and dirty programming, but if you are going 
to be using it in a more general environment you should also put in some 
error checking to make sure you have tuples, etc.

 >>> x = [('hello', 2), ('goodbye', 3), ('python', 1)]
 >>> x.sort(compare)
 >>> x
[('python', 1), ('hello', 2), ('goodbye', 3)]

Personally I prefer this way as it makes my code more readable (especially 
if I use a better name than 'compare' :)

Hope this helps
Fred Milgrom






More information about the Tutor mailing list