标签:hash
统计字符出现次数并排序
class Hist(dict):
def add(self, item, increment=1):
"""increase num"""
self[item] = increment + self.get(item, 0)
def counts(self, reverse=False):
"""return"""
aux = [(self[k], k) for k in self]
aux.sort()
if reverse:
aux.reverse()
return [k for v, k in aux]
test = Hist()
test.add(5)
test.add(5)
test.add(1)
test.add(1)
test.add(5)
test.add(2)
print test
print test.counts()
[8, 2, 1, 7, 5, 4, 3, 9]
[(8, 0), (2, 1), (1, 2), (7, 3), (5, 4), (4, 5), (3, 6), (9, 7)]
[(1, 2), (2, 1), (3, 6), (4, 5), (5, 4), (7, 3), (8, 0), (9, 7)]
[2, 1, 6, 5, 4, 3, 0, 7]
标签:hash
原文地址:http://blog.csdn.net/u014539401/article/details/45817793