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

时间:2015-05-18 12:58:07   收藏:0   阅读:148

统计字符出现次数并排序

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]    
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!