Learning Python via a little word frequency program

Fredrik Lundh fredrik at pythonware.com
Wed Jan 9 07:14:26 EST 2008


Andrew Savige wrote:

> Neat. Is there any way to use sorted() with multiple sort keys? ...

sure!  just return the "composite key" as a tuple:

    # sort on descending count, ascending name
    deco = sorted(freq.items(), key=lambda x: (-x[1], x[0]))

(when comparing tuples, Python first compares the first item from each 
tuple.  if they're equal, it continues with the second item, and so on).

</F>




More information about the Python-list mailing list