[Tutor] Sorting
Kalle Svensson
kalle@lysator.liu.se
Wed, 31 Jul 2002 06:16:13 +0200
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
[Timothy M. Brauch]
> I would like to be able to sort the list of Participants in
> Competition in specific ways. I am pretty sure it can be done with
> sort(cmpfunc), but I can't figure it out and documention on the
> cmpfunc for sort seems to be lacking, or hard to find. Here is an
> example session of what I would like to have.
[snip]
Maybe simple compare functions like these would work?
def compare_by_team(x, y):
return cmp(x.team, y.team)
def compare_by_name(x, y):
return (cmp(x.last_name, y.last_name) or
cmp(x.first_name, y.first_name))
They mostly use the builtin function cmp that is the standard compare
function. lst.sort() and lst.sort(cmp) are equivalent.
compare_by_name is a bit clever with the or. It could be written as
def compare_by_name(x, y):
ln = cmp(x.last_name, y.last_name)
if not ln: # Last names are equal
return cmp(x.first_name, y.first_name)
return ln
which is perhaps more clear.
> I tried writing sort_by_team() by scratch using if statements, but
> somehow there is an error in my statements and possibly my identing,
> but at something like 15 lines to sort a list, I think I am on the
> wrong track. So, I would greatly appreciate it if someone could
> help me with the sort().
Generally, if you post more of your code and error messages, it is
easier to help. This time, I don't think that it mattered. Just a
tip for the future.
Peace,
Kalle
- --
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>
iD8DBQE9R2SDdNeA1787sd0RAruWAJ0fbES9KN1LSnWnKHuXyjG8wgDryACgkWMh
44mgjNBmriZIoCrloxDV778=
=bnBJ
-----END PGP SIGNATURE-----