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

Python中获取列表众数及出现次数的更高效优雅实现方案

更高效优雅的众数及出现次数实现方法

你的原方案确实存在重复遍历列表的问题,两次lst.count加上max内部的多次count调用,时间复杂度达到O(n²),对于大列表效率很低。下面是几种更高效的实现方式:

方法1:使用collections.Counter(推荐)

Python标准库的collections.Counter专门用于统计元素频率,只需遍历一次列表就能完成统计,然后通过most_common(1)直接获取频率最高的元素及其次数:

from collections import Counter

lst = [1, 2, 3, 2, 2, 4]
mode, count = Counter(lst).most_common(1)[0]
print(mode, count)  # 输出:2 3
  • 时间复杂度:O(n),仅需遍历一次列表统计频率
  • 代码简洁直观,是处理这类问题的标准方案

方法2:手动遍历统计(无需额外模块)

如果不想导入模块,可以手动维护频率字典,遍历一次列表的同时跟踪当前的众数和最大次数:

def find_mode_and_count(lst):
    freq_dict = {}
    max_count = 0
    mode = None
    for item in lst:
        # 更新当前元素的频率
        freq_dict[item] = freq_dict.get(item, 0) + 1
        # 如果当前元素频率超过最大值,更新众数和最大次数
        if freq_dict[item] > max_count:
            max_count = freq_dict[item]
            mode = item
    return mode, max_count

lst = [1, 2, 3, 2, 2, 4]
mode, count = find_mode_and_count(lst)
print(mode, count)  # 输出:2 3
  • 时间复杂度同样是O(n),适合受限环境下使用
  • 若需要处理多个众数(多个元素出现次数相同且均为最大值),可以调整逻辑,将所有符合条件的元素收集起来

处理多众数场景

如果列表存在多个出现次数相同的众数,比如lst = [1,1,2,2,3],可以用以下方式获取所有众数及其次数:

from collections import Counter

lst = [1,1,2,2,3]
counter = Counter(lst)
max_freq = max(counter.values())
all_modes = [(item, freq) for item, freq in counter.items() if freq == max_freq]
print(all_modes)  # 输出:[(1, 2), (2, 2)]

原方案的效率问题说明

你的原代码中:

  • max(set(lst), key=lst.count)会对集合中的每个元素调用lst.count,每个count操作需要遍历整个列表(O(n)),集合大小若为k,这一步的时间复杂度是O(kn)
  • 后续再调用一次lst.count又要遍历一次列表(O(n))
  • 最坏情况下(列表所有元素唯一),时间复杂度会达到O(n²),远不如上述O(n)的方案高效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 06:55:13