python3 中的Counter函数


Counter函数用来遍历列表中的所有元素 并将元素出现的次数记录下来

 

例如:

1.

alist = [1,1,3,99,88,2,2,2]
from collections import Counter
print(Counter(alist))

#输出结果为:({2: 3,1: 2,3: 1,99: 1,88: 1})

 代表 2出现3次 1出现2次 3 99 88分别出现1次

2.

print(Counter(alist).most_common(1))

#输出结果为:[(2,3)]

 代表 取出出现次数最多的元素

3.

print(Counter(alist).most_common(2))

#输出结果为:[(2,3),(1,2)]

  代表 取出出现次数最多的前两个元素


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM