>>> def numeric_compare (x, y): ... return x -y >>> sorted([5,2,4,1,3], cmp =numeric_compare) [1, 2, 3, 4, 5] >>> def reverse_numeric(x, y): ... return y -x >>> sorted([5,2,4,1,3], cmp =reverse_numeric) [5, 4, 3, 2, 1] def cmp_to_key (mycmp): 'Convert a cmp= function into a key= function ' classK : def __init__ (self, obj,*args): self.obj =obj def __lt__ (self, other): return mycmp( self.obj, other.obj)<0 def __gt__ (self, other): return mycmp( self.obj, other.obj)>0 def __eq__ (self, other): return mycmp( self.obj, other.obj)==0 def __le__ (self, other): return mycmp( self.obj, other.obj)<=0 def __ge__ (self, other): return mycmp( self.obj, other.obj)>=0 def __ne__ (self, other): return mycmp( self.obj, other.obj)!=0 return K >>> sorted([5,2,4,1,3], key=cmp_to_key(reverse_numeric)) [5, 4, 3, 2, 1] >>> data =[('red',1), ( 'blue',1), ( 'red',2), ( 'blue',2)] >>> standard_way=sorted(data, key =itemgetter(0), reverse = True ) >>> double_reversed=list(reversed(sorted(reversed(data), key =itemgetter(0 )))) >>> assert standard_way==double_reversed >>> standard_way [('red', 1), ('red', 2), ('blue', 1), ('blue', 2)] 5 • The sort routines are guaranteed to use$_{__lt__()}$ when making comparisons between two objects. So, it is easy to add a standard sort order to a class by defining an$_{__lt__()}$ method: • The reverse parameter still maintains sort stability (so that records with equal keys retain the original order). Interestingly, that effect can be simulated without the parameter by using the builtin$_{reversed()}$ function twice: • For locale aware sorting, use locale.strxfrm() for a key function or locale.strcoll() for a comparison function. 8 Odd and Ends In Python 3.2, the$_{functools.cmp_to_key()}$ function was added to the$_{functools}$ module in the standard library. To convert to a key function, just wrap the old comparison function: When porting code from Python 2.x to 3.x, the situation can arise when you have the user supplying a comparison function and you need to convert that to a key function. The following wrapper makes that easy to do: Or you can reverse the order of comparison with: