ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> python-list
python-list
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

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved