Re: Sort documentation inaccurate?
by David Glasser other posts by this author
Sep 26 2001 10:00PM messages near this date
RE: Sort documentation inaccurate?
|
RE: Sort documentation inaccurate?
Bruce Dawson <comments@[...].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@[...].net http://www.davidglasser.net/
--
http://mail.python.org/mailman/listinfo/python-list
Thread:
Bruce Dawson
Bruce Dawson
Tim Peters
David Glasser
Sean 'Shaleh' Perry
|