python - 如何使用python查找列表中最高数字出现的次数?
问题描述
例如,如果一个列表是:list = [1, 2, 3, 4, 4]
如何计算数字 4 出现的次数,而不指定它。使用max(list)
或类似的东西。
解决方案
试试这个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 中预定义的,您将覆盖它自己的功能。
推荐阅读
- javascript - 在没有ajax调用的情况下使用带有@HTML.BeginForm的formdata append
- awk - 在运行时在 awk 脚本中捕获或评估错误的正则表达式字符串
- powershell - 服务不显示可以正确关闭
- sql-server - SSIS - 脚本任务...使用此版本集成服务不支持的 15.0 版脚本
- html - htmlTable() 输出不会进入 RStudio 查看器:而是在控制台中将输出显示为 HTML 代码
- redirect - 如何在codeigniter中重定向页面
- python - 检查 Django 表单中的值是否相同
- c# - 如何取消正在运行的任务?
- android - 如何为 Google Maps Android API UrlTileProvider 设置 SSL 证书?
- java - 为什么不应直接在应用程序中使用 spring 安全配置?