[Tutor] high score lists
Jacob S.
keridee at jayco.net
Sat Apr 16 03:40:16 CEST 2005
> You can think of the "key" option like this: when sort comes to compare
> elements x and y it gives you the option of telling *what* you want to
> compare about x and y. You might, for example, want to sort a list of
> strings based on their *length* not on their alphabetical position. To do
> so, write a 1-argument function that returns the length of a string:
>
> ###
> Python 2.4 (#1, Apr 4 2005, 13:57:19)
> [GCC 3.3 20030304 (Apple Computer, Inc. build 1493)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> l=['sea', 'd', 'bee']
> >>> l.sort() #the normal sort
> >>> l
> ['bee', 'd', 'sea']
> >>> def strlen(x): # the 1-argument function
> ... return len(x)
> ...
> >>> l.sort(key=strlen)
> >>> l
> ['d', 'sea', 'bee'] #the length sort; it's stable so sea is still
> before bee
> >>> def length_alph(x): #'key' function if you want length first and
> then alphabetical
> ... return (len(x),x)
> ...
> >>> l.sort(key=length_alph); l
> ['d', 'bee', 'sea']
> ###
Great. len is a function though. Why use a second layer of function when
len is a function in itself?
>>> l = ['d','sea','bee']
>>> l.sort(key=len)
>>> l
['d', 'bee', 'sea']
>>>
Jacob
More information about the Tutor
mailing list