python之获取list中元素出现的次数


迅速获取list中元素出现的次数
from collections import Counter
def counter(arr):
    return Counter(arr).most_common(1)      # 返回出现频率最高的一个数
  

例如:
from collections import Counter

arr = [1,2,3,1,2,3,4,1,1]
def counter(arr):
    return Counter(arr).most_common(1)
print(counter(arr))

返回结果:[(1, 4)]  括号第一个数 是频率最高的数 第二个数是 出现次数

可以在 return Counter(arr).most_common(1)[0][0] 获取到 出现频率最高的数


免责声明!

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



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