python中 collections模块的 Counter使用方法

版权声明:转载请说明地址,谢谢! https://blog.csdn.net/larykaiy/article/details/82941501

Counter 集成于 dict 类,因此也可以使用字典的方法,此类返回一个以元素为 key 、元素个数为 value 的 Counter 对象集合
most_common(n) 可以返回数量最多的前 n 个元素
统计某数字出现的次数,举例说明

from random import randint
from collections import Counter

data = [randint(0, 20) for _ in range(30)]
c = dict.fromkeys(data, 0)

c2 = Counter(data)
print(c2)

c3 = c2.most_common(3)  # 不改变c2
print(c3)

Counter({8: 5, 5: 3, 6: 2, 7: 2, 9: 2, 10: 2, 14: 2, 15: 2, 16: 2, 17: 2, 0: 1, 2: 1, 4: 1, 13: 1, 18: 1, 19: 1})
[(8, 5), (5, 3), (6, 2)]

猜你喜欢

转载自blog.csdn.net/larykaiy/article/details/82941501