Python面試題之統(tǒng)計哈希列表中最多元素
問題
有一個元素序列,想知道在序列中出現(xiàn)次數(shù)最多的元素是什么
解決方案
collections 模塊中的 Counter 類轉(zhuǎn)讓給女士為此問題所設(shè)計的。它甚至有一個非常方便的most_common()方法可以直接告訴我們答案。
為了說明用法,假設(shè)有一個列表,列表中是一系列的單詞,我們想找出哪些單詞出現(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 對象提供任何可哈希的對象序列做為輸入。在底層實現(xiàn)中,Counter 是一個字典,在元素和它們出現(xiàn)的次數(shù)間做了映射。例:
word_counter['not'] # 1 word_counter['eyes'] # 8
如果想手動增加計數(shù),只能簡單地自增即可:
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對象還可以同各種數(shù)學運算操作結(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)計哈希列表中最多元素的詳細內(nèi)容,更多關(guān)于Python哈希列表最多元素統(tǒng)計的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python實現(xiàn)線性判別分析(LDA)的MATLAB方式
今天小編大家分享一篇Python實現(xiàn)線性判別分析(LDA)的MATLAB方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12如何使用 Python 讀取文件和照片的創(chuàng)建日期
這篇文章主要介紹了如何使用 Python 讀取文件和照片的創(chuàng)建日期,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09Django調(diào)用百度AI接口實現(xiàn)人臉注冊登錄代碼實例
這篇文章主要介紹了Django調(diào)用百度AI接口實現(xiàn)人臉注冊登錄,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-04-04python實戰(zhàn)之PyQt5實現(xiàn)漫畫臉
本文詳細講解了python實戰(zhàn)之PyQt5實現(xiàn)漫畫臉的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-12-12