前言
Python包含6種內(nèi)置的序列:列表、元組、字符串 、Unicode字符串、buffer對象、xrange對象。在序列中的每個元素都有自己的編號。列表與元組的區(qū)別在于,列表是可以修改,而組元不可修改。理論上幾乎所有情況下元組都可以用列表來代替。有個例外是但元組作為字典的鍵時,在這種情況下,因?yàn)殒I不可修改,所以就不能使用列表。
我們在一些統(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 類就是專門為這類問題而設(shè)計的, 它甚至有一個有用的 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:雙向隊(duì)列。引入自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和負(fù)數(shù))。Counter類和其他語言的bags或multisets很相似。
為了演示,先假設(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 Counterword_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還有一個比較高級的功能,支持?jǐn)?shù)學(xué)算術(shù)符的相加相減。
>>> a = Counter(words)>>> b = Counter(morewords)>>> aCounter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2,"you're": 1, "don't": 1, 'under': 1, 'not': 1})>>> bCounter({'eyes': 1, 'looking': 1, 'are': 1, 'in': 1, 'not': 1, 'you': 1,'my': 1, 'why': 1})>>> # Combine counts>>> c = a + b>>> cCounter({'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>>> dCounter({'eyes': 7, 'the': 5, 'look': 4, 'into': 3, 'my': 2, 'around': 2,"you're": 1, "don't": 1, 'under': 1})>>>
新聞熱點(diǎn)
疑難解答
圖片精選