首页 > 解决方案 > 如何使用python查找列表中最高数字出现的次数?

问题描述

例如,如果一个列表是:list = [1, 2, 3, 4, 4] 如何计算数字 4 出现的次数,而不指定它。使用max(list)或类似的东西。

标签: pythonlistmax

解决方案


试试这个max

l = [1,2,3,4,4]
num = max(l, key=lambda x:l.count(x))  # num will be 4

你可以得到num.

l.count(num)  # this wil returns 2

另一方面,正如@buddemat 所说(这里),最好:

from collections import Counter      
                                                                                                                                                                                                                                         
l = [1,2,3,4,4]
c = Counter(l)  
c.most_common()[0]

会给你

(4,2) # 4 is a maximum number and 2 is number of occurrence.

另请注意:

不要list用作变量名,list它是在 python 中预定义的,您将覆盖它自己的功能。


推荐阅读