[Tutor] Re: sorting nested tuples

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sat Oct 18 04:09:59 EDT 2003



On Sat, 18 Oct 2003, Alfred Milgrom wrote:

> 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).

By the way, we can say this another way by taking advantage of the
built-in cmp()  comparison function:

###
def compare(a, b):
    return cmp(a[1], b[1])
###



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

How about compare_second_component()?  *grin*


Talk to you later!




More information about the Tutor mailing list