计数项目并按关联排序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了计数项目并按关联排序相关的知识,希望对你有一定的参考价值。

  1. ## {{{ http://code.activestate.com/recipes/52231/ (r1)
  2. class Counter:
  3. def __init__(self):
  4. self.dict = {}
  5. def add(self,item):
  6. count = self.dict.setdefault(item,0)
  7. self.dict[item] = count + 1
  8. def counts(self,desc=None):
  9. '''Returns list of keys, sorted by values.
  10. Feed a 1 if you want a descending sort.'''
  11. i = map(lambda t: list(t),self.dict.items())
  12. map(lambda r: r.reverse(),i)
  13. i.sort()
  14. if desc:
  15. i.reverse()
  16. return i
  17.  
  18. if __name__ == '__main__':
  19.  
  20. '''Produces:
  21.  
  22. >>> Ascending count:
  23. [[1, 'but'], [1, 'it'], [1, 'not.'], [1, 'now'], [1, 'test,'], [1, 'test.'], [1, 'was'], [2, 'Hello'], [2, 'a'], [2, 'is'], [2, 'there'], [2, 'this']]
  24. Descending count:
  25. [[2, 'this'], [2, 'there'], [2, 'is'], [2, 'a'], [2, 'Hello'], [1, 'was'], [1, 'test.'], [1, 'test,'], [1, 'now'], [1, 'not.'], [1, 'it'], [1, 'but']]
  26. '''
  27.  
  28. sentence = "Hello there this is a test. Hello there this was a test, but now it is not."
  29. words = sentence.split()
  30. c=Counter()
  31. for word in words:
  32. c.add(word)
  33. print "Ascending count:"
  34. print c.counts()
  35. print "Descending count:"
  36. print c.counts(1)
  37. ## end of http://code.activestate.com/recipes/52231/ }}}

以上是关于计数项目并按关联排序的主要内容,如果未能解决你的问题,请参考以下文章

Sequelize - 按关联计数排序

NSFetchRequest 分组并按 dateField 计数

如何对每个表进行分组计数并按列打印? [复制]

查找关联计数大于零的所有记录

sql 按计数获取日期的博客存档格式,并按月/年分组

nsfetchedresultscontroller 根据项目计数对部分进行排序