Quoting Max Noel <[EMAIL PROTECTED]>:

> On Apr 15, 2005, at 01:33, D. Hartley wrote:
> > (I also
> > just ended up writing the list like [score,user] because I couldnt
> > figure out how to get it to sort by the second half of the tuple. I
> > need a better tutorial book, I think!)
>       I'm still using Python 2.3, so someone else will have to tell you what
> the "key" argument is.

Interestingly, the key argument is the solution to this problem:

>>> arr = zip(range(10), range(10,0,-1))
>>> arr
[(0, 10), (1, 9), (2, 8), (3, 7), (4, 6), (5, 5), (6, 4), (7, 3), (8, 2), (9, 
1)]
>>> arr.sort(key=lambda x: x[1])
>>> arr
[(9, 1), (8, 2), (7, 3), (6, 4), (5, 5), (4, 6), (3, 7), (2, 8), (1, 9), (0, 
10)]

Basically, key takes a function which, given a list element, returns the value
you actually want to sort by.
 
> - Your 2 best friends are the interactive Python shell, and the help() 
> function.

True, although help(sort) could be more helpful...

>>> help([].sort)

Help on built-in function sort:

sort(...)
    L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
    cmp(x, y) -> -1, 0, 1

>>>

-- 
John.
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to