Counter(计数器):用于追踪值的出现次数
Counter类
创建一个Counter类
import collections obj = collections.Counter('aabbccc') print(obj) #输出:Counter({'c': 3, 'a': 2, 'b': 2})
继承dict类,所以它能使用dict类里面的方法
import collections obj = collections.Counter('aabbccc') print(sorted(obj.elements())) #输出:['a', 'a', 'b', 'b', 'c', 'c', 'c'] for k in obj.elements(): #遍历打印obj所有元素 print(k)
most_common(指定一个参数n,列出前n个元素,不指定参数,则列出所有)
import collections obj = collections.Counter('aabbbcccc') print(obj.most_common(2)) #输出:[('c', 4), ('b', 3)]
import collections obj = collections.Counter('aabbbcccc') print(obj.items()) for k,v in obj.items(): print(k,v) #输出:dict_items([('b', 3), ('c', 4), ('a', 2)]) # b 3 # c 4 # a 2