[Tutor] samples on sort method of sequence object.

Hugo Arts hugo.yoshi at gmail.com
Tue Jan 12 18:00:06 CET 2010


On Tue, Jan 12, 2010 at 3:39 PM, Make Twilight <ph4nut at gmail.com> wrote:
> Hi,there:
>  The document of
> Python.org[http://docs.python.org/library/stdtypes.html] says that:
>
> <snip>
>
>  I can understand how to use parameters of cmp and reverse,except the
> key parameter...
>  Would anyone give me an example of using sort method with key parameter?
>  Thanks!
>

key has essentially the same purpose as cmp, but it works more
efficiently because it only calls the key function once for each value
in the sequence. A simple though maybe not very useful example could
be sorting lists of integers in such a way that the list with the
lowest sum comes first:

>>> seqs = [(2, 0, 0), (3, 5, 5), (1, 100, 100)]
>>> seqs.sort()
>>> seqs
[(1, 100, 100), (2, 0, 0), (3, 5, 5)]
>>> seqs.sort(key=sum)
>>> seqs
[(2, 0, 0), (3, 5, 5), (1, 100, 100)]

the sort function calls the key function sum(s) for every s in
sequence, then sorts the list using the result of that call. An
equivalent example using the cmp function could be this one:

>>> seqs.sort(cmp=lambda x, y: cmp(sum(x), sum(y))

Another example given by the docs is using the str.lower function.
Here it is in action:

>>> s = list("A string WitH Some Capitals")
>>> s.sort(key=str.lower)
>>> s
[' ', ' ', ' ', ' ', 'A', 'a', 'a', 'C', 'e', 'g', 'H', 'i', 'i', 'i',
'l', 'm', 'n', 'o', 'p', 'r', 's', 'S', 's', 't', 't', 't', 'W']
>>> s.sort()
>>> s
[' ', ' ', ' ', ' ', 'A', 'C', 'H', 'S', 'W', 'a', 'a', 'e', 'g', 'i',
'i', 'i', 'l', 'm', 'n', 'o', 'p', 'r', 's', 's', 't', 't', 't']

Normally, when sorting a string, capital letters come before regular
ones. With the key() argument, the sorting is done between the lowered
versions of each letter, so the sort becomes case insensitive. Note
that this doesn't actually change our string, it only changes what
exactly is used for our comparisons. Again, same sort using the cmp
argument:

s.sort(cmp=lambda x, y: cmp(x.lower(), y.lower())

Hugo


More information about the Tutor mailing list