Python 获取列表最高频元素的三种实现方案
在 Python 开发中,统计列表内元素的出现频率是一项常见需求。本文详细解析了三种获取最高频元素的方法:手动构建字典、利用 setdefault 函数简化逻辑,以及使用 collections 模块的 Counter 类。重点介绍了 Counter 模块的高级用法,包括 most_common 函数的参数设置与返回值类型,帮助开发者根据实际需求选择最合适的实现方案。
手动构建字典统计
最基础的方式是通过遍历列表,利用字典记录每个元素的出现次数。具体逻辑为:若元素不在字典的键中,则将其设为键,值设为该元素在列表中的 count 计数。这种方式直观易懂,但效率较低,因为每次调用 count 都会重新遍历列表。
# 字典方法
words = [
'my', 'skills', 'are', 'poor', 'I', 'am', 'poor', 'I',
'need', 'skills', 'more', 'my', 'ability', 'are',
'so', 'poor'
]
dict1 = {}
for i in words:
if i not in dict1.keys():
dict1[i] = words.count(i)
print(dict1)使用 setdefault 简化逻辑
利用字典的 setdefault 函数可以简化代码。该函数的原理是:若键不存在,添加键并将值设为默认值 0;若键存在,setdefault 不生效并累加次数。这种方式避免了重复遍历列表,提高了效率。
words = [
'my', 'skills', 'are', 'poor', 'I', 'am', 'poor', 'I',
'need', 'skills', 'more', 'my', 'ability', 'are',
'so', 'poor'
]
d = dict()
for item in words:
# setdefault()函数,如果键不存在于字典中,将会添加键并将值设为默认值
d[item] = d.setdefault(item, 0) + 1
print(d)利用 collections.Counter 模块
Python 标准库中的 collections 模块提供了 Counter 类,可直接计数并自动排序。Counter 类型支持相加和相减操作,但不支持 Counter 与 int 类型的乘法运算。使用 most_common 可输出频率最大的 n 个元素,返回结果类型为 list。
from collections import Counter
words = [
'my', 'skills', 'are', 'poor', 'I', 'am', 'poor', 'I',
'need', 'skills', 'more', 'my', 'ability', 'are',
'so', 'poor'
]
collection_words = Counter(words)
print(collection_words)
print(type(collection_words))获取最高频元素
通过 most_common 方法,可以指定返回前 n 个最高频元素。例如,获取出现次数最多的 3 个元素:
most_counterNum = collection_words.most_common(3)
print(most_counterNum)
print(type(most_counterNum))以上就是 Python 找出列表中出现次数最多的元素三种方式的详细内容,更多关于 Python 列表统计的资料请关注本站其它相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













