使用Counter()统计各个元素出现的次数

5年以前  |  阅读数:460 次  |  编程语言:Python 
from collections import Counter()

data = [randint(1,10) for _ in range(10)]
# 得到的dic2和方法1的dic一样,一条代码解决问题!
dic2 = Counter(data)
# 并且还可以使用most_common(n)方法来直接统计出出现频率最高的n个元素
dic2.most_common(2)
# 输出一个list ,其中的元素为(key,value)的键值对,类似[(6, 4), (3, 2)]这样

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8