Counter是dict的子类,一般用于统计,默认排序是从大到小
from collections import Counter # 输入iterable对象即可 str_counter = Counter('dgwjgdsjgdjksgdsjgdgshfdsghfd') # 直接统计出结果,吊了一逼 print(str_counter) # Counter({'d': 7, 'g': 7, 's': 5, 'j': 4, 'h': 2, 'f': 2, 'w': 1, 'k': 1}) # update() 将两个counter对象中的数据一起统计 str_counter.update(Counter('sasfagsfa')) print(str_counter) # Counter({'g': 8, 's': 8, 'd': 7, 'j': 4, 'f': 4, 'a': 3, 'h': 2, 'w': 1, 'k': 1}) # 取top 5 top_5 = str_counter.most_common(5) print(top_5) # [('g', 8), ('s', 8), ('d', 7), ('j', 4), ('f', 4)]
日拱一卒无有尽,功不唐捐终入海