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

如何使用Python查找众数及该众数的出现次数

Python 数组众数及出现次数实现方案

下面给出两种可直接运行的实现方式,兼容单众数、多众数场景:

方法1:使用标准库collections.Counter实现(推荐)

Counter是Python内置的计数工具,代码简洁高效:

from collections import Counter

def get_array_mode(arr):
    # 空数组判断,避免运行异常
    if not arr:
        return [], 0
    # 统计所有元素出现次数
    count_result = Counter(arr)
    # 取最高出现频次
    max_occur = max(count_result.values())
    # 收集所有频次等于最高值的元素(兼容多众数场景)
    mode_list = [item for item, count in count_result.items() if count == max_occur]
    return mode_list, max_occur

调用示例

# 测试用例1:单众数
test_arr1 = [1,2,2,3]
modes, count = get_array_mode(test_arr1)
print(modes, count) # 输出 [2], 2

# 测试用例2:多众数
test_arr2 = [1,1,2,2,3]
modes, count = get_array_mode(test_arr2)
print(modes, count) # 输出 [1,2], 2

方法2:纯基础语法实现(无依赖,适合原理学习)

手动实现计数逻辑,不需要导入任何库:

def get_array_mode(arr):
    if not arr:
        return [], 0
    count_dict = {}
    # 遍历数组统计每个元素出现次数
    for item in arr:
        count_dict[item] = count_dict.get(item, 0) + 1
    # 取最高频次、收集众数
    max_occur = max(count_dict.values())
    mode_list = [k for k, v in count_dict.items() if v == max_occur]
    return mode_list, max_occur

两种方法的返回结果格式一致,第一个返回值是众数列表(可能有1个或多个元素),第二个返回值是众数的出现次数。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 17:30:04