Sort documentation inaccurate?
David Glasser
news at davidglasser.net
Wed Sep 26 18:00:39 EDT 2001
Bruce Dawson <comments at cygnus-software.com> wrote:
> >>> mylist = [1, 2, 3, 5, 4, 6]
> >>> def compare1(x, y):
> ... return x < y
> ...
> >>> mylist.sort(compare1)
> >>> mylist
> [1, 2, 3, 5, 4, 6]
The comparison "x < y" can return two values: 1 if x < y, and 0 if
x >= y. But a sort function really needs to be more specific,
differentiating between x < y, x > y, and x == y. The standard for sort
functions, based on C's strcmp, is to return:
-1 if x < y
0 if x == y
+1 if x > y
(It appears that any negative value is as good as -1, and any positive
for +1, but the documentation just say those specific values.) This is,
as you said, so a function can do something along the lines of "return x
- y".
The really good news, though, is that you can ignore most of this by
using Python's cmp function. For example, to sort by absolute value:
>>> x = [1, 0, -2, 52, -32, 4]
>>> def abssort(x, y):
... return cmp(abs(x), abs(y))
...
>>> x.sort(abssort)
>>> x
[0, 1, -2, 4, -32, 52]
--
David Glasser
news at davidglasser.net http://www.davidglasser.net/
More information about the Python-list
mailing list