Learning Python via a little word frequency program
Andrew Savige
ajsavige at yahoo.com.au
Wed Jan 9 07:08:14 EST 2008
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".
>> 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
More information about the Python-list
mailing list