在 Python 中查找列表中出现频率最高的元素

pythonserver side programmingprogramming更新于 2026/1/22 17:48:17

在本文中,我们将了解如何查找给定列表中出现频率最高的元素。换句话说,就是出现频率最高的元素。

使用 max 和 count

我们应用 set 函数来获取列表中的唯一元素,然后记录列表中的每个元素。最后应用 max 函数来获取出现频率最高的元素。

示例

# 给定列表
listA = [45, 20, 11, 50, 17, 45, 50,13, 45]
print("给定列表:\n",listA)
res = max(set(listA), key = listA.count)
print("Element with highest frequency:\n",res)

输出

运行上述代码得到以下结果 −

给定列表:
[45, 20, 11, 50, 17, 45, 50, 13, 45]
Element with highest frequency:
45

使用 Counter

我们使用集合中的计数器函数。然后应用最常用的函数来获取最终结果。

示例

from collections import Counter
# 给定列表
listA = [45, 20, 11, 50, 17, 45, 50,13, 45]
print("给定列表:\n",listA)
occurence_count = Counter(listA)
res=occurence_count.most_common(1)[0][0]
print("Element with highest frequency:\n",res)

输出

运行上述代码得到以下结果 −

给定列表:
[45, 20, 11, 50, 17, 45, 50, 13, 45]
Element with highest frequency:
45

使用 mode

这是一种直接的方法,我们使用统计模块中的模式函数。它直接给出结果。

示例

from statistics import mode
# 给定列表
listA = [45, 20, 11, 50, 17, 45, 50,13, 45]
print("给定列表:\n",listA)
res=mode(listA)
print("Element with highest frequency:\n",res)

输出

运行上述代码得到以下结果 −

给定列表:
[45, 20, 11, 50, 17, 45, 50, 13, 45]
Element with highest frequency:
45

相关文章


有用资源