码迷,mamicode.com
首页 > 编程语言 > 详细

统计字符出现次数并排序(hash)

时间:2015-05-18 12:58:07      阅读:148      评论:0      收藏:0      [点我收藏+]

标签: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)

标签:hash

原文地址:http://blog.csdn.net/u014539401/article/details/45817793

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!