Python 列表中出现频率最高的元素
pythonserver side programmingprogramming更新于 2025/11/23 18:20:17
许多统计数据分析都试图在给定的值列表中找到出现频率最高的值。Python 提供了多种方法,我们可以使用这些方法从给定的列表中找到这样的值。以下是这些方法。
使用 Counter
collections 模块中的 Counter 函数有一个选项,可以直接在给定的列表中找到最常见的元素。我们有 most_common 函数,我们只为一个出现频率最高的元素传递一个参数 1,如果我们需要两个出现频率最高的元素,则传递 2。
示例
from collections import Counter
# 给定列表
listA = ['Mon', 'Tue','Mon', 9, 3, 3]
print("Given list : ",listA)
# 为每个元素添加另一个元素
Newlist1 = Counter(listA).most_common(1)
Newlist2 = Counter(listA).most_common(2)
# 结果
print("New list after duplication: ",Newlist1)
print("New list after duplication: ",Newlist2)
输出
运行上述代码得到以下结果 −
Given list : ['Mon', 'Tue', 'Mon', 9, 3, 3]
New list after duplication: [('Mon', 2)]
New list after duplication: [('Mon', 2), (3, 2)]
使用模式
模式是 Python 统计模块中提供的统计函数。它将输出频率最高的元素。如果有多个这样的元素,则首先遇到的频率最高的元素将是输出。
示例
from statistics import mode
# 给定列表
listA = ['Mon', 'Tue','Mon', 9, 3, 3]
listB = [3,3,'Mon', 'Tue','Mon', 9]
print("Given listA : ",listA)
print("Given listB : ",listB)
# 为每个元素添加另一个元素
Newlist1 = mode(listA)
Newlist2 = mode(listB)
# 结果
print("New listA after duplication: ",Newlist1)
print("New listB after duplication: ",Newlist2)
输出
运行上述代码得到以下结果 −
Given listA : ['Mon', 'Tue', 'Mon', 9, 3, 3] Given listB : [3, 3, 'Mon', 'Tue', 'Mon', 9] New listA after duplication: Mon New listB after duplication: 3
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

