You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3新手求助:统计数组中出现次数最多的字符串的次数

解决Python统计数组中元素最高出现次数的问题

你已经用到了collections.Counter这个合适的工具,只需要在它的基础上提取最大值就能满足需求,具体实现如下:

基础实现

from collections import Counter

names = ['Bob', 'Bob', 'Ben', 'Alex', 'Bob']
counts = Counter(names)
# 从统计结果中提取所有出现次数的最大值
max_count = max(counts.values())
print(max_count)  # 输出3

适配空数组的健壮版本(可选)

如果需要处理空数组的情况,避免报错,可以加个简单判断:

from collections import Counter

def get_max_occurrence(name_list):
    if not name_list:
        return 0  # 空数组返回0,可根据实际需求调整返回值
    counts = Counter(name_list)
    return max(counts.values())

# 测试示例
print(get_max_occurrence(['Bob', 'Bob', 'Ben', 'Alex', 'Bob']))  # 输出3
print(get_max_occurrence([]))  # 输出0

补充说明

你之前看到的示例只是打印了完整的Counter统计结果,而我们需要的是从这些统计值里提取最大的那个数字,用max(counts.values())就能直接拿到目标结果。

内容的提问来源于stack exchange,提问作者Tester1994

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:35:20