Python面試題之統(tǒng)計(jì)哈希列表中最多元素
問題
有一個(gè)元素序列,想知道在序列中出現(xiàn)次數(shù)最多的元素是什么
解決方案
collections 模塊中的 Counter 類轉(zhuǎn)讓給女士為此問題所設(shè)計(jì)的。它甚至有一個(gè)非常方便的most_common()方法可以直接告訴我們答案。
為了說明用法,假設(shè)有一個(gè)列表,列表中是一系列的單詞,我們想找出哪些單詞出現(xiàn)的最為頻繁。
下面是我們的做法:
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 對(duì)象提供任何可哈希的對(duì)象序列做為輸入。在底層實(shí)現(xiàn)中,Counter 是一個(gè)字典,在元素和它們出現(xiàn)的次數(shù)間做了映射。例:
word_counter['not'] # 1 word_counter['eyes'] # 8
如果想手動(dòng)增加計(jì)數(shù),只能簡(jiǎn)單地自增即可:
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對(duì)象還可以同各種數(shù)學(xué)運(yùn)算操作結(jié)合起來使用:
>>> 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面試題之統(tǒng)計(jì)哈希列表中最多元素的詳細(xì)內(nèi)容,更多關(guān)于Python哈希列表最多元素統(tǒng)計(jì)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
基于Keras的格式化輸出Loss實(shí)現(xiàn)方式
這篇文章主要介紹了基于Keras的格式化輸出Loss實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06
python GUI庫圖形界面開發(fā)之PyQt5布局控件QHBoxLayout詳細(xì)使用方法與實(shí)例
不到20行代碼用Python做一個(gè)智能聊天機(jī)器人

