[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: Learning Python via a little word frequency program

Andrew Savige

1/9/2008 12:08:00 PM

Fredrik Lundh wrote:> # sort items on descending count> deco = sorted(freq.items(), key=lambda x: -x[1])Neat. Is there any way to use sorted() with multiple sort keys? ...Given that the spec calls for sorting by _two_ keys: first byfrequency (descending), then by name (ascending). To clarify:kevin : 3jock : 2andrew : 1bill : 1fred : 1freddy : 1is correct, while:kevin : 3jock : 2bill : 1andrew : 1fred : 1freddy : 1is incorrect because "andrew 1" must appear before "bill 1".>> Finally, I might replace:>> >> for v, k in deco:>> print "%-10s: %d" % (k, -v)>> >> with:>> >> print "\n"..join("%-10s: %d" % (k, -v) for v, k in deco)>> why?No good reason, unless performance is significantly different.The first seems clearer to me. Just wondering what other folks think.Thanks,/- Make the switch to the world's best email. Get the new Yahoo!7 Mail now. www.yahoo7.com.au/worldsbestemail
1 Answer

Peter Otten

1/9/2008 12:22:00 PM

0

Andrew Savige wrote:

> Fredrik Lundh wrote:
>
>> # sort items on descending count
>> deco = sorted(freq.items(), key=lambda x: -x[1])
>
> Neat. Is there any way to use sorted() with multiple sort keys? ...
> Given that the spec calls for sorting by _two_ keys: first by
> frequency (descending), then by name (ascending). To clarify:
>
> kevin : 3
> jock : 2
> andrew : 1
> bill : 1
> fred : 1
> freddy : 1
>
> is correct, while:
>
> kevin : 3
> jock : 2
> bill : 1
> andrew : 1
> fred : 1
> freddy : 1
>
> is incorrect because "andrew 1" must appear before "bill 1".

You can sort twice (on the name, then on the number) or use a more complex
key:

>>> for n, v in sorted(freq.items(), key=lambda (n, v): (-v, n)):
.... print n, v
....
kevin 3
jock 2
andrew 1
bill 1
fred 1
freddy 1

>>> items = freq.items()
>>> items.sort(key=itemgetter(0))
>>> items.sort(key=itemgetter(1), reverse=True)
>>> for n, v in items:
.... print n, v
....
kevin 3
jock 2
andrew 1
bill 1
fred 1
freddy 1

Peter