1.collections模塊
collections模塊自Python 2.4版本開始被引入,包含了dict、set、list、tuple以外的一些特殊的容器類型,分別是:
OrderedDict類:排序字典,是字典的子類。引入自2.7。
namedtuple()函數(shù):命名元組,是一個(gè)工廠函數(shù)。引入自2.6。
Counter類:為hashable對(duì)象計(jì)數(shù),是字典的子類。引入自2.7。
deque:雙向隊(duì)列。引入自2.4。
defaultdict:使用工廠函數(shù)創(chuàng)建字典,使不用考慮缺失的字典鍵。引入自2.5。
文檔參見:http://docs.python.org/2/library/collections.html。
2.Counter類
Counter類的目的是用來跟蹤值出現(xiàn)的次數(shù)。它是一個(gè)無序的容器類型,以字典的鍵值對(duì)形式存儲(chǔ),其中元素作為key,其計(jì)數(shù)作為value。計(jì)數(shù)值可以是任意的Interger(包括0和負(fù)數(shù))。Counter類和其他語言的bags或multisets很相似。
2.1 創(chuàng)建
下面的代碼說明了Counter類創(chuàng)建的四種方法:
Counter類的創(chuàng)建Python
1
2
3
4
5
6
7
8
9
|
>>> c = Counter() # 創(chuàng)建一個(gè)空的Counter類 >>> c = Counter( 'gallahad' ) # 從一個(gè)可iterable對(duì)象(list、tuple、dict、字符串等)創(chuàng)建 >>> c = Counter({ 'a' : 4 , 'b' : 2 }) # 從一個(gè)字典對(duì)象創(chuàng)建 >>> c = Counter(a = 4 , b = 2 ) # 從一組鍵值對(duì)創(chuàng)建 >>> c = Counter() # 創(chuàng)建一個(gè)空的Counter類 >>> c = Counter( 'gallahad' ) # 從一個(gè)可iterable對(duì)象(list、tuple、dict、字符串等)創(chuàng)建 >>> c = Counter({ 'a' : 4 , 'b' : 2 }) # 從一個(gè)字典對(duì)象創(chuàng)建 >>> c = Counter(a = 4 , b = 2 ) # 從一組鍵值對(duì)創(chuàng)建 |
當(dāng)所訪問的鍵不存在時(shí),返回0,而不是KeyError;否則返回它的計(jì)數(shù)。
計(jì)數(shù)值的訪問Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
>>> c = Counter( "abcdefgab" ) >>> c[ "a" ] 2 >>> c[ "c" ] 1 >>> c[ "h" ] 0 >>> c = Counter( "abcdefgab" ) >>> c[ "a" ] 2 >>> c[ "c" ] 1 >>> c[ "h" ] 0 |
2.3 計(jì)數(shù)器的更新(update和subtract)
可以使用一個(gè)iterable對(duì)象或者另一個(gè)Counter對(duì)象來更新鍵值。
計(jì)數(shù)器的更新包括增加和減少兩種。其中,增加使用update()方法:
計(jì)數(shù)器的更新(update)Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
>>> c = Counter( 'which' ) >>> c.update( 'witch' ) # 使用另一個(gè)iterable對(duì)象更新 >>> c[ 'h' ] 3 >>> d = Counter( 'watch' ) >>> c.update(d) # 使用另一個(gè)Counter對(duì)象更新 >>> c[ 'h' ] 4 >>> c = Counter( 'which' ) >>> c.update( 'witch' ) # 使用另一個(gè)iterable對(duì)象更新 >>> c[ 'h' ] 3 >>> d = Counter( 'watch' ) >>> c.update(d) # 使用另一個(gè)Counter對(duì)象更新 >>> c[ 'h' ] 4 |
減少則使用subtract()方法:
計(jì)數(shù)器的更新(subtract)Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
>>> c = Counter( 'which' ) >>> c.subtract( 'witch' ) # 使用另一個(gè)iterable對(duì)象更新 >>> c[ 'h' ] 1 >>> d = Counter( 'watch' ) >>> c.subtract(d) # 使用另一個(gè)Counter對(duì)象更新 >>> c[ 'a' ] - 1 >>> c = Counter( 'which' ) >>> c.subtract( 'witch' ) # 使用另一個(gè)iterable對(duì)象更新 >>> c[ 'h' ] 1 >>> d = Counter( 'watch' ) >>> c.subtract(d) # 使用另一個(gè)Counter對(duì)象更新 >>> c[ 'a' ] - 1 |
2.4 鍵的刪除
當(dāng)計(jì)數(shù)值為0時(shí),并不意味著元素被刪除,刪除元素應(yīng)當(dāng)使用del。
鍵的刪除Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
>>> c = Counter( "abcdcba" ) >>> c Counter({ 'a' : 2 , 'c' : 2 , 'b' : 2 , 'd' : 1 }) >>> c[ "b" ] = 0 >>> c Counter({ 'a' : 2 , 'c' : 2 , 'd' : 1 , 'b' : 0 }) >>> del c[ "a" ] >>> c Counter({ 'c' : 2 , 'b' : 2 , 'd' : 1 }) >>> c = Counter( "abcdcba" ) >>> c Counter({ 'a' : 2 , 'c' : 2 , 'b' : 2 , 'd' : 1 }) >>> c[ "b" ] = 0 >>> c Counter({ 'a' : 2 , 'c' : 2 , 'd' : 1 , 'b' : 0 }) >>> del c[ "a" ] >>> c Counter({ 'c' : 2 , 'b' : 2 , 'd' : 1 }) |
2.5 elements()
返回一個(gè)迭代器。元素被重復(fù)了多少次,在該迭代器中就包含多少個(gè)該元素。所有元素按照字母序排序,個(gè)數(shù)小于1的元素不被包含。
1
2
3
4
5
6
7
8
9
|
elements()方法Python >>> c = Counter(a = 4 , b = 2 , c = 0 , d = - 2 ) >>> list (c.elements()) [ 'a' , 'a' , 'a' , 'a' , 'b' , 'b' ] >>> c = Counter(a = 4 , b = 2 , c = 0 , d = - 2 ) >>> list (c.elements()) [ 'a' , 'a' , 'a' , 'a' , 'b' , 'b' ] |
2.6 most_common([n])
返回一個(gè)TopN列表。如果n沒有被指定,則返回所有元素。當(dāng)多個(gè)元素計(jì)數(shù)值相同時(shí),按照字母序排列。
most_common()方法Python
1
2
3
4
5
6
7
8
9
10
11
|
>>> c = Counter( 'abracadabra' ) >>> c.most_common() [( 'a' , 5 ), ( 'r' , 2 ), ( 'b' , 2 ), ( 'c' , 1 ), ( 'd' , 1 )] >>> c.most_common( 3 ) [( 'a' , 5 ), ( 'r' , 2 ), ( 'b' , 2 )] >>> c = Counter( 'abracadabra' ) >>> c.most_common() [( 'a' , 5 ), ( 'r' , 2 ), ( 'b' , 2 ), ( 'c' , 1 ), ( 'd' , 1 )] >>> c.most_common( 3 ) [( 'a' , 5 ), ( 'r' , 2 ), ( 'b' , 2 )] |
2.7 fromkeys
未實(shí)現(xiàn)的類方法。
2.8 淺拷貝copy
淺拷貝copyPython
1
2
3
4
5
6
7
8
9
10
11
12
13
|
>>> c = Counter( "abcdcba" ) >>> c Counter({ 'a' : 2 , 'c' : 2 , 'b' : 2 , 'd' : 1 }) >>> d = c.copy() >>> d Counter({ 'a' : 2 , 'c' : 2 , 'b' : 2 , 'd' : 1 }) >>> c = Counter( "abcdcba" ) >>> c Counter({ 'a' : 2 , 'c' : 2 , 'b' : 2 , 'd' : 1 }) >>> d = c.copy() >>> d Counter({ 'a' : 2 , 'c' : 2 , 'b' : 2 , 'd' : 1 }) |
2.9 算術(shù)和集合操作
+、-、&、|操作也可以用于Counter。其中&和|操作分別返回兩個(gè)Counter對(duì)象各元素的最小值和最大值。需要注意的是,得到的Counter對(duì)象將刪除小于1的元素。
Counter對(duì)象的算術(shù)和集合操作Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
>>> c = Counter(a = 3 , b = 1 ) >>> d = Counter(a = 1 , b = 2 ) >>> c + d # c[x] + d[x] Counter({ 'a' : 4 , 'b' : 3 }) >>> c - d # subtract(只保留正數(shù)計(jì)數(shù)的元素) Counter({ 'a' : 2 }) >>> c & d # 交集: min(c[x], d[x]) Counter({ 'a' : 1 , 'b' : 1 }) >>> c | d # 并集: max(c[x], d[x]) Counter({ 'a' : 3 , 'b' : 2 }) >>> c = Counter(a = 3 , b = 1 ) >>> d = Counter(a = 1 , b = 2 ) >>> c + d # c[x] + d[x] Counter({ 'a' : 4 , 'b' : 3 }) >>> c - d # subtract(只保留正數(shù)計(jì)數(shù)的元素) Counter({ 'a' : 2 }) >>> c & d # 交集: min(c[x], d[x]) Counter({ 'a' : 1 , 'b' : 1 }) >>> c | d # 并集: max(c[x], d[x]) Counter({ 'a' : 3 , 'b' : 2 }) |
3.常用操作
下面是一些Counter類的常用操作,來源于Python官方文檔
Counter類常用操作Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
sum (c.values()) # 所有計(jì)數(shù)的總數(shù) c.clear() # 重置Counter對(duì)象,注意不是刪除 list (c) # 將c中的鍵轉(zhuǎn)為列表 set (c) # 將c中的鍵轉(zhuǎn)為set dict (c) # 將c中的鍵值對(duì)轉(zhuǎn)為字典 c.items() # 轉(zhuǎn)為(elem, cnt)格式的列表 Counter( dict (list_of_pairs)) # 從(elem, cnt)格式的列表轉(zhuǎn)換為Counter類對(duì)象 c.most_common()[: - n: - 1 ] # 取出計(jì)數(shù)最少的n個(gè)元素 c + = Counter() # 移除0和負(fù)值 sum (c.values()) # 所有計(jì)數(shù)的總數(shù) c.clear() # 重置Counter對(duì)象,注意不是刪除 list (c) # 將c中的鍵轉(zhuǎn)為列表 set (c) # 將c中的鍵轉(zhuǎn)為set dict (c) # 將c中的鍵值對(duì)轉(zhuǎn)為字典 c.items() # 轉(zhuǎn)為(elem, cnt)格式的列表 Counter( dict (list_of_pairs)) # 從(elem, cnt)格式的列表轉(zhuǎn)換為Counter類對(duì)象 c.most_common()[: - n: - 1 ] # 取出計(jì)數(shù)最少的n個(gè)元素 c + = Counter() # 移除0和負(fù)值 |
4.實(shí)例
4.1判斷兩個(gè)字符串是否由相同的字母集合調(diào)換順序而成的(anagram)
1
2
3
4
5
6
7
8
9
10
|
def is_anagram(word1, word2): """Checks whether the words are anagrams. word1: string word2: string returns: boolean """ return Counter(word1) = = Counter(word2) |
Counter如果傳入的參數(shù)是字符串,就會(huì)統(tǒng)計(jì)字符串中每個(gè)字符出現(xiàn)的次數(shù),如果兩個(gè)字符串由相同的字母集合顛倒順序而成,則它們Counter的結(jié)果應(yīng)該是一樣的。
4.2多元集合(MultiSets)
multiset是相同元素可以出現(xiàn)多次的集合,Counter可以非常自然地用來表示multiset。并且可以將Counter擴(kuò)展,使之擁有set的一些操作如is_subset。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class Multiset(Counter): """A multiset is a set where elements can appear more than once.""" def is_subset( self , other): """Checks whether self is a subset of other. other: Multiset returns: boolean """ for char, count in self .items(): if other[char] < count: return False return True # map the <= operator to is_subset __le__ = is_subset |
4.3概率質(zhì)量函數(shù)
概率質(zhì)量函數(shù)(probability mass function,簡(jiǎn)寫為pmf)是離散隨機(jī)變量在各特定取值上的概率。可以利用Counter表示概率質(zhì)量函數(shù)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
class Pmf(Counter): """A Counter with probabilities.""" def normalize( self ): """Normalizes the PMF so the probabilities add to 1.""" total = float ( sum ( self .values())) for key in self : self [key] / = total def __add__( self , other): """Adds two distributions. The result is the distribution of sums of values from the two distributions. other: Pmf returns: new Pmf """ pmf = Pmf() for key1, prob1 in self .items(): for key2, prob2 in other.items(): pmf[key1 + key2] + = prob1 * prob2 return pmf def __hash__( self ): """Returns an integer hash value.""" return id ( self ) def __eq__( self , other): return self is other def render( self ): """Returns values and their probabilities, suitable for plotting.""" return zip ( * sorted ( self .items())) |
normalize: 歸一化隨機(jī)變量出現(xiàn)的概率,使它們之和為1
add: 返回的是兩個(gè)隨機(jī)變量分布兩兩組合之和的新的概率質(zhì)量函數(shù)
render: 返回按值排序的(value, probability)的組合對(duì),方便畫圖的時(shí)候使用
下面以骰子(ps: 這個(gè)竟然念tou子。。。)作為例子。
1
2
3
4
5
|
d6 = Pmf([ 1 , 2 , 3 , 4 , 5 , 6 ]) d6.normalize() d6.name = 'one die' print (d6) Pmf({ 1 : 0.16666666666666666 , 2 : 0.16666666666666666 , 3 : 0.16666666666666666 , 4 : 0.16666666666666666 , 5 : 0.16666666666666666 , 6 : 0.16666666666666666 }) |
使用add,我們可以計(jì)算出兩個(gè)骰子和的分布:
1
2
3
4
5
|
d6_twice = d6 + d6 d6_twice.name = 'two dices' for key, prob in d6_twice.items(): print (key, prob) |
借助numpy.sum,我們可以直接計(jì)算三個(gè)骰子和的分布:
1
2
3
|
import numpy as np d6_thrice = np. sum ([d6] * 3 ) d6_thrice.name = 'three dices' |
最后可以使用render返回結(jié)果,利用matplotlib把結(jié)果畫圖表示出來:
1
2
3
4
5
6
7
8
|
for die in [d6, d6_twice, d6_thrice]: xs, ys = die.render() pyplot.plot(xs, ys, label = die.name, linewidth = 3 , alpha = 0.5 ) pyplot.xlabel( 'Total' ) pyplot.ylabel( 'Probability' ) pyplot.legend() pyplot.show() |
結(jié)果如下:
4.4貝葉斯統(tǒng)計(jì)
我們繼續(xù)用擲骰子的例子來說明用Counter如何實(shí)現(xiàn)貝葉斯統(tǒng)計(jì)。現(xiàn)在假設(shè),一個(gè)盒子中有5種不同的骰子,分別是:4面、6面、8面、12面和20面的。假設(shè)我們隨機(jī)從盒子中取出一個(gè)骰子,投出的骰子的點(diǎn)數(shù)為6。那么,取得那5個(gè)不同骰子的概率分別是多少?
(1)首先,我們需要生成每個(gè)骰子的概率質(zhì)量函數(shù):
1
2
3
4
5
6
7
8
9
|
def make_die(num_sides): die = Pmf( range ( 1 , num_sides + 1 )) die.name = 'd%d' % num_sides die.normalize() return die dice = [make_die(x) for x in [ 4 , 6 , 8 , 12 , 20 ]] print (dice) |
(2)接下來,定義一個(gè)抽象類Suite。Suite是一個(gè)概率質(zhì)量函數(shù)表示了一組假設(shè)(hypotheses)及其概率分布。Suite類包含一個(gè)bayesian_update函數(shù),用來基于新的數(shù)據(jù)來更新假設(shè)(hypotheses)的概率。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class Suite(Pmf): """Map from hypothesis to probability.""" def bayesian_update( self , data): """Performs a Bayesian update. Note: called bayesian_update to avoid overriding dict.update data: result of a die roll """ for hypo in self : like = self .likelihood(data, hypo) self [hypo] * = like self .normalize() |
其中的likelihood函數(shù)由各個(gè)類繼承后,自己實(shí)現(xiàn)不同的計(jì)算方法。
(3)定義DiceSuite類,它繼承了類Suite。
1
2
3
4
5
6
7
8
9
|
class DiceSuite(Suite): def likelihood( self , data, hypo): """Computes the likelihood of the data under the hypothesis. data: result of a die roll hypo: Die object """ return hypo[data] |
并且實(shí)現(xiàn)了likelihood函數(shù),其中傳入的兩個(gè)參數(shù)為: data: 觀察到的骰子擲出的點(diǎn)數(shù),如本例中的6 hypo: 可能擲出的那個(gè)骰子
(4)將第一步創(chuàng)建的dice傳給DiceSuite,然后根據(jù)給定的值,就可以得出相應(yīng)的結(jié)果。
1
2
3
4
5
6
7
8
9
10
11
12
|
dice_suite = DiceSuite(dice) dice_suite.bayesian_update( 6 ) for die, prob in sorted (dice_suite.items()): print die.name, prob d4 0.0 d6 0.392156862745 d8 0.294117647059 d12 0.196078431373 d20 0.117647058824 |
正如,我們所期望的4個(gè)面的骰子的概率為0(因?yàn)?個(gè)面的點(diǎn)數(shù)只可能為0~4),而6個(gè)面的和8個(gè)面的概率最大。 現(xiàn)在,假設(shè)我們又?jǐn)S了一次骰子,這次出現(xiàn)的點(diǎn)數(shù)是8,重新計(jì)算概率:
1
2
3
4
5
6
7
8
9
10
11
|
dice_suite.bayesian_update( 8 ) for die, prob in sorted (dice_suite.items()): print die.name, prob d4 0.0 d6 0.0 d8 0.623268698061 d12 0.277008310249 d20 0.0997229916898 |
現(xiàn)在可以看到6個(gè)面的骰子也被排除了。8個(gè)面的骰子是最有可能的。
以上的幾個(gè)例子,展示了Counter的用處。實(shí)際中,Counter的使用還比較少,如果能夠恰當(dāng)?shù)氖褂闷饋韺?huì)帶來非常多的方便。