计数项目并按关联排序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了计数项目并按关联排序相关的知识,希望对你有一定的参考价值。
## {{{ http://code.activestate.com/recipes/52231/ (r1) class Counter: def __init__(self): self.dict = {} def add(self,item): count = self.dict.setdefault(item,0) self.dict[item] = count + 1 def counts(self,desc=None): '''Returns list of keys, sorted by values. Feed a 1 if you want a descending sort.''' i = map(lambda t: list(t),self.dict.items()) map(lambda r: r.reverse(),i) i.sort() if desc: i.reverse() return i if __name__ == '__main__': '''Produces: >>> Ascending count: [[1, 'but'], [1, 'it'], [1, 'not.'], [1, 'now'], [1, 'test,'], [1, 'test.'], [1, 'was'], [2, 'Hello'], [2, 'a'], [2, 'is'], [2, 'there'], [2, 'this']] Descending count: [[2, 'this'], [2, 'there'], [2, 'is'], [2, 'a'], [2, 'Hello'], [1, 'was'], [1, 'test.'], [1, 'test,'], [1, 'now'], [1, 'not.'], [1, 'it'], [1, 'but']] ''' sentence = "Hello there this is a test. Hello there this was a test, but now it is not." words = sentence.split() c=Counter() for word in words: c.add(word) print "Ascending count:" print c.counts() print "Descending count:" print c.counts(1) ## end of http://code.activestate.com/recipes/52231/ }}}
以上是关于计数项目并按关联排序的主要内容,如果未能解决你的问题,请参考以下文章