利用Python找出序列中出現(xiàn)最多的元素示例代碼
前言
Python包含6種內(nèi)置的序列:列表、元組、字符串 、Unicode字符串、buffer對象、xrange對象。在序列中的每個元素都有自己的編號。列表與元組的區(qū)別在于,列表是可以修改,而組元不可修改。理論上幾乎所有情況下元組都可以用列表來代替。有個例外是但元組作為字典的鍵時,在這種情況下,因為鍵不可修改,所以就不能使用列表。
我們在一些統(tǒng)計工作或者分析過程中,有事會遇到要統(tǒng)計一個序列中出現(xiàn)最多次的元素,比如一段英文中,查詢出現(xiàn)最多的詞是什么,及每個詞出現(xiàn)的次數(shù)。一遍的做法為,將每個此作為key,出現(xiàn)一次,value增加1。
例如:
morewords = ['why','are','you','not','looking','in','my','eyes'] for word in morewords: word_counts[word] += 1
collections.Counter
類就是專門為這類問題而設計的, 它甚至有一個有用的 most_common()
方法直接給了你答案。
collections模塊
collections模塊自Python 2.4版本開始被引入,包含了dict、set、list、tuple以外的一些特殊的容器類型,分別是:
- OrderedDict類:排序字典,是字典的子類。引入自2.7。
- namedtuple()函數(shù):命名元組,是一個工廠函數(shù)。引入自2.6。
- Counter類:為hashable對象計數(shù),是字典的子類。引入自2.7。
- deque:雙向隊列。引入自2.4。
- defaultdict:使用工廠函數(shù)創(chuàng)建字典,使不用考慮缺失的字典鍵。引入自2.5。
文檔參見:http://docs.python.org/2/library/collections.html。
Counter類
Counter類的目的是用來跟蹤值出現(xiàn)的次數(shù)。它是一個無序的容器類型,以字典的鍵值對形式存儲,其中元素作為key,其計數(shù)作為value。計數(shù)值可以是任意的Interger(包括0和負數(shù))。Counter類和其他語言的bags或multisets很相似。
為了演示,先假設你有一個單詞列表并且想找出哪個單詞出現(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) # 出現(xiàn)頻率最高的3個單詞 top_three = word_counts.most_common(3) print(top_three) # Outputs [('eyes', 8), ('the', 5), ('look', 4)]
另外collections.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}) >>>
參考文檔:
https://docs.python.org/3/library/collections.html
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
- Python要求O(n)復雜度求無序列表中第K的大元素實例
- python-序列解包(對可迭代元素的快速取值方法)
- Python如何篩選序列中的元素的方法實現(xiàn)
- Python cookbook(數(shù)據(jù)結構與算法)將名稱映射到序列元素中的方法
- python如何統(tǒng)計序列中元素
- Python cookbook(數(shù)據(jù)結構與算法)篩選及提取序列中元素的方法
- Python cookbook(數(shù)據(jù)結構與算法)找出序列中出現(xiàn)次數(shù)最多的元素算法示例
- Python cookbook(數(shù)據(jù)結構與算法)從序列中移除重復項且保持元素間順序不變的方法
- python實現(xiàn)獲取序列中最小的幾個元素
- Python過濾序列元素的方法
相關文章
Python并發(fā)concurrent.futures和asyncio實例
這篇文章主要介紹了Python并發(fā)concurrent.futures和asyncio實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05