compare function in sort function of lists

Sean 'Shaleh' Perry shalehperry at attbi.com
Fri Apr 5 17:35:58 EST 2002


On 05-Apr-2002 Gabe Newcomb wrote:
> Hi all:
>       I'm trying to sort a list numerically, e.g.,  so that 11 comes
> AFTER 2. The documentation says I need to pass sort() a compare
> function...but I can't find an example of this.
> 
> This should be an easy one for you folks :)
> 

>>> l = [1,5,11,2,67,23]
>>> l.sort()
>>> l
[1, 2, 5, 11, 23, 67]
>>> def comp(a,b): # sort in reverse
...   if b < a: return -1
...   elif b == a: return 0
...   else: return 1
... 
>>> l.sort(comp)
>>> l
[67, 23, 11, 5, 2, 1]

p.s. try the tutor at python.org list for simple things like this





More information about the Python-list mailing list