letter frequency counter / your thoughts..

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Wed May 7 18:21:24 EDT 2008


On 7 mai, 23:50, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
(snip)
> Someone else suggested the heapq module, which is a good approach
> though it might be considered a little bit high-tech.  If you
> want to use sorting (conceptually simpler), you could use the
> sorted function instead of the in-place sorting function:
>
>       # return the second element of a 2-tuple.  Note how we
>       # use tuple unpacking: this is really a function of one argument
>       # (the tuple) but we specify the arg as (a,b) so the tuple
>       # is automatically unpacked on entry to the function.
>       # this is a limited form of the "pattern matching" found in
>       # languages like ML.
>       def snd((a,b)): return b

operator.itemgetter does this already

>       return sorted(dic.iteritems, key=snd, reverse=True)[-3:]

you want to actually call iteritems here !-)

        return sorted(dic.iteritems(), key=operator.itemgetter(1),
reverse=True)

Thanks for reminding me the 'key' argument to sorted anyway - I too
often tend to forget it.



More information about the Python-list mailing list