Python面试题之统计哈希列表中最多元素
本文详解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哈希列表最多元素统计的资料请关注本站其它相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













