Python面試題之統計哈希列表中最多元素
更新時間:2021年09月29日 10:14:09 作者:沉沉沉小姐
這篇文章主要為大家講解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 對象提供任何可哈希的對象序列做為輸入。在底層實現中,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 讀取文件和照片的創(chuàng)建日期
這篇文章主要介紹了如何使用 Python 讀取文件和照片的創(chuàng)建日期,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09

