Python面試題之統(tǒng)計哈希列表中最多元素
問題
有一個元素序列,想知道在序列中出現(xiàn)次數(shù)最多的元素是什么
解決方案
collections 模塊中的 Counter 類轉(zhuǎn)讓給女士為此問題所設計的。它甚至有一個非常方便的most_common()方法可以直接告訴我們答案。
為了說明用法,假設有一個列表,列表中是一系列的單詞,我們想找出哪些單詞出現(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ù)學運算操作結合起來使用:
>>> 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)容,更多關于Python哈希列表最多元素統(tǒng)計的資料請關注本站其它相關文章!
版權聲明:本站文章來源標注為YINGSOO的內(nèi)容版權均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。