collections模块是python的标准库,实现了特定目标的容易,以提供Python标准内建容器 dict , list , set , 和 tuple 的替代选择。
collections.Counter()
字典的子类,实现了可哈希对象的计数功能,返回一个字典,key是元素,value是出现的次数。
>>> from collections import Counter
>>> Counter('dhueifcsad')
Counter({'d': 2, 'h': 1, 'u': 1, 'e': 1, 'i': 1, 'f': 1, 'c': 1, 's': 1, 'a': 1})
>>> Counter([1,2,3,41,23,4,1,3,4])
Counter({1: 2, 3: 2, 4: 2, 2: 1, 41: 1, 23: 1})
Counter().most_common(n):
返回Counter中出现次数最多的元素,返回为列表,列表元素为元组
>>> a= Counter([1,2,3,41,23,4,1,3,4])
>>> a.most_common(2)
[(1, 2), (3, 2)]
>>> a
Counter({1: 2, 3: 2, 4: 2, 2: 1, 41: 1, 23: 1})