Python面试题之统计哈希列表中最多元素

周予安
周予安
发布时间:2026-10-14| 5人浏览过
原创

本文详解Python中统计列表最高频元素的方法,重点介绍collections模块下的Counter类及其most_common()用法。通过代码示例展示如何手动计数、使用update()更新及执行数学运算,解决面试中关于序列频率统计的常见问题。

问题

给定一个元素序列,需要确定其中出现频率最高的元素。

解决方案

Python标准库collections模块中的Counter类专门为此类问题设计。它提供了一个便捷的most_common()方法,可直接返回出现频率最高的元素及其计数。

为了演示具体用法,假设有一个包含多个单词的列表,目标是找出其中出现频率最高的单词。

具体实现步骤如下:


words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
] 
from collections import Counter
word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three)
# Outputs [('eyes', 8), ('the', 5), ('look', 4)]

Counter对象可以接受任何可哈希对象的序列作为输入。其底层基于字典实现,建立了元素与出现次数之间的映射关系。例如:


word_counter['not']
# 1
word_counter['eyes']
# 8

若需手动增加特定元素的计数,可直接对其值进行自增操作:


morewords = ['why','are','you','not','looking','in','my','eyes']
for word in morewords:
    word_counts[word] += 1 
print(word_counts['eyes'])
# 9

另一种更新计数的方法是调用update()方法:


word_counts.update(morewords)

Counter对象还支持各种数学运算操作,例如合并或相减计数:


>>> a = Counter(words)
>>> b = Counter(morewords)
>>> a
Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2,
"you're": 1, "don't": 1, 'under': 1, 'not': 1})
>>> b
Counter({'eyes': 1, 'looking': 1, 'are': 1, 'in': 1, 'not': 1, 'you': 1,
'my': 1, 'why': 1})
>>> # Combine counts
>>> c = a + b
>>> c
Counter({'eyes': 9, 'the': 5, 'look': 4, 'my': 4, 'into': 3, 'not': 2,
'around': 2, "you're": 1, "don't": 1, 'in': 1, 'why': 1,
'looking': 1, 'are': 1, 'under': 1, 'you': 1})
>>> # Subtract counts
>>> d = a - b
>>> d
Counter({'eyes': 7, 'the': 5, 'look': 4, 'into': 3, 'my': 2, 'around': 2,
"you're": 1, "don't": 1, 'under': 1})

以上为Python面试题之统计哈希列表中最多元素的详细内容,更多关于Python哈希列表最多元素统计的资料请关注本站其它相关文章!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。