tallying occurrences in list
Paul Rubin
no.email at nospam.invalid
Fri Jun 4 14:28:15 EDT 2010
kj <no.email at please.post> writes:
> 1. is there a standard name for it?
I don't know of one, or a stdlib for it, but it's pretty trivial.
> def tally(c):
> t = dict()
> for x in c:
> t[x] = t.get(x, 0) + 1
> return sorted(t.items(), key=lambda x: (-x[1], x[0]))
I like to use defaultdict and tuple unpacking for code like that:
from collections import defaultdict
def tally(c):
t = defaultdict(int)
for x in c:
t[x] += 1
return sorted(t.iteritems(), key=lambda (k,v): (-v, k))
More information about the Python-list
mailing list