使用できますcollections.Counter()
(py2.7で導入):
In [52]: from collections import Counter
In [53]: c=Counter("aaabbc")
In [54]: c
Out[54]: Counter({'a': 3, 'b': 2, 'c': 1})
In [55]: c.most_common()
Out[55]: [('a', 3), ('b', 2), ('c', 1)]
そしてpy2.6では次を使用できますcollections.defaultdict
:
In [58]: from collections import defaultdict
In [59]: strs="aaabbc"
In [61]: dic=defaultdict(int)
In [62]: for x in strs:
....: dic[x]+=1
....:
In [63]: dic
Out[63]: defaultdict(<type 'int'>, {'a': 3, 'c': 1, 'b': 2})
In [64]: from operator import itemgetter
In [66]: sorted(dic.items(),reverse=True,key=itemgetter(1))
Out[66]: [('a', 3), ('b', 2), ('c', 1)]