Python中Collections模塊的Counter容器類使用教程

分類:IT技術 時間:2016-10-07

1.collections模塊

collections模塊自python 2.4版本開始被引入,包含了dict、set、list、tuple以外的一些特殊的容器類型,分別是:

OrderedDict類:排序字典,是字典的子類。引入自2.7。
namedtuple()函數:命名元組,是一個工廠函數。引入自2.6。
Counter類:為hashable對象計數,是字典的子類。引入自2.7。
deque:雙向隊列。引入自2.4。
defaultdict:使用工廠函數創建字典,使不用考慮缺失的字典鍵。引入自2.5。
文檔參見:http://docs.python.org/2/library/collections.html。

2.Counter類

Counter類的目的是用來跟蹤值出現的次數。它是一個無序的容器類型,以字典的鍵值對形式存儲,其中元素作為key,其計數作為value。計數值可以是任意的Interger(包括0和負數)。Counter類和其他語言的bags或multisets很相似。

2.1 創建

下面的代碼說明了Counter類創建的四種方法:

Counter類的創建Python

>>> c = Counter() # 創建一個空的Counter類
>>> c = Counter('gallahad') # 從一個可iterable對象(list、tuple、dict、字符串等)創建
>>> c = Counter({'a': 4, 'b': 2}) # 從一個字典對象創建
>>> c = Counter(a=4, b=2) # 從一組鍵值對創建

>>> c = Counter() # 創建一個空的Counter類
>>> c = Counter('gallahad') # 從一個可iterable對象(list、tuple、dict、字符串等)創建
>>> c = Counter({'a': 4, 'b': 2}) # 從一個字典對象創建
>>> c = Counter(a=4, b=2) # 從一組鍵值對創建

2.2 計數值的訪問與缺失的鍵

當所訪問的鍵不存在時,返回0,而不是KeyError;否則返回它的計數。

計數值的訪問Python

>>> 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 計數器的更新(update和subtract)

可以使用一個iterable對象或者另一個Counter對象來更新鍵值。

計數器的更新包括增加和減少兩種。其中,增加使用update()方法:

計數器的更新(update)Python

>>> c = Counter('which')
>>> c.update('witch') # 使用另一個iterable對象更新
>>> c['h']
3
>>> d = Counter('watch')
>>> c.update(d) # 使用另一個Counter對象更新
>>> c['h']
4

>>> c = Counter('which')
>>> c.update('witch') # 使用另一個iterable對象更新
>>> c['h']
3
>>> d = Counter('watch')
>>> c.update(d) # 使用另一個Counter對象更新
>>> c['h']
4

 
減少則使用subtract()方法:

計數器的更新(subtract)Python

>>> c = Counter('which')
>>> c.subtract('witch') # 使用另一個iterable對象更新
>>> c['h']
1
>>> d = Counter('watch')
>>> c.subtract(d) # 使用另一個Counter對象更新
>>> c['a']
-1

>>> c = Counter('which')
>>> c.subtract('witch') # 使用另一個iterable對象更新
>>> c['h']
1
>>> d = Counter('watch')
>>> c.subtract(d) # 使用另一個Counter對象更新
>>> c['a']
-1

2.4 鍵的刪除

當計數值為0時,並不意味著元素被刪除,刪除元素應當使用del。

鍵的刪除Python

>>> 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()

返回一個叠代器。元素被重復了多少次,在該叠代器中就包含多少個該元素。所有元素按照字母序排序,個數小於1的元素不被包含。

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])

返回一個TopN列表。如果n沒有被指定,則返回所有元素。當多個元素計數值相同時,按照字母序排列。

most_common()方法Python

>>> 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

未實現的類方法。

2.8 淺拷貝copy

淺拷貝copyPython

>>> 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 算術和集合操作

+、-、&、|操作也可以用於Counter。其中&和|操作分別返回兩個Counter對象各元素的最小值和最大值。需要註意的是,得到的Counter對象將刪除小於1的元素。

Counter對象的算術和集合操作Python

>>> 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(只保留正數計數的元素)
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(只保留正數計數的元素)
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

sum(c.values()) # 所有計數的總數
c.clear() # 重置Counter對象,註意不是刪除
list(c) # 將c中的鍵轉為列表
set(c) # 將c中的鍵轉為set
dict(c) # 將c中的鍵值對轉為字典
c.items() # 轉為(elem, cnt)格式的列表
Counter(dict(list_of_pairs)) # 從(elem, cnt)格式的列表轉換為Counter類對象
c.most_common()[:-n:-1] # 取出計數最少的n個元素
c += Counter() # 移除0和負值

sum(c.values()) # 所有計數的總數
c.clear() # 重置Counter對象,註意不是刪除
list(c) # 將c中的鍵轉為列表
set(c) # 將c中的鍵轉為set
dict(c) # 將c中的鍵值對轉為字典
c.items() # 轉為(elem, cnt)格式的列表
Counter(dict(list_of_pairs)) # 從(elem, cnt)格式的列表轉換為Counter類對象
c.most_common()[:-n:-1] # 取出計數最少的n個元素
c += Counter() # 移除0和負值

4.實例
4.1判斷兩個字符串是否由相同的字母集合調換順序而成的(anagram)

def is_anagram(word1, word2):
  """Checks whether the words are anagrams.

  word1: string
  word2: string

  returns: boolean
  """

  return Counter(word1) == Counter(word2)

Counter如果傳入的參數是字符串,就會統計字符串中每個字符出現的次數,如果兩個字符串由相同的字母集合顛倒順序而成,則它們Counter的結果應該是一樣的。

4.2多元集合(MultiSets)
multiset是相同元素可以出現多次的集合,Counter可以非常自然地用來表示multiset。並且可以將Counter擴展,使之擁有set的一些操作如is_subset。

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概率質量函數
概率質量函數(probability mass function,簡寫為pmf)是離散隨機變量在各特定取值上的概率。可以利用Counter表示概率質量函數。

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: 歸一化隨機變量出現的概率,使它們之和為1
add: 返回的是兩個隨機變量分布兩兩組合之和的新的概率質量函數
render: 返回按值排序的(value, probability)的組合對,方便畫圖的時候使用
下面以骰子(ps: 這個竟然念tou子。。。)作為例子。

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,我們可以計算出兩個骰子和的分布:

d6_twice = d6 + d6
d6_twice.name = 'two dices'

for key, prob in d6_twice.items():
  print(key, prob)

借助numpy.sum,我們可以直接計算三個骰子和的分布:

import numpy as np
d6_thrice = np.sum([d6]*3)
d6_thrice.name = 'three dices'

最後可以使用render返回結果,利用matplotlib把結果畫圖表示出來:

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()

結果如下:

2016531165107908.png (613×458)

4.4貝葉斯統計
我們繼續用擲骰子的例子來說明用Counter如何實現貝葉斯統計。現在假設,一個盒子中有5種不同的骰子,分別是:4面、6面、8面、12面和20面的。假設我們隨機從盒子中取出一個骰子,投出的骰子的點數為6。那麽,取得那5個不同骰子的概率分別是多少?
(1)首先,我們需要生成每個骰子的概率質量函數:

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)接下來,定義一個抽象類Suite。Suite是一個概率質量函數表示了一組假設(hypotheses)及其概率分布。Suite類包含一個bayesian_update函數,用來基於新的數據來更新假設(hypotheses)的概率。

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函數由各個類繼承後,自己實現不同的計算方法。

(3)定義DiceSuite類,它繼承了類Suite。

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]

並且實現了likelihood函數,其中傳入的兩個參數為: data: 觀察到的骰子擲出的點數,如本例中的6 hypo: 可能擲出的那個骰子

(4)將第一步創建的dice傳給DiceSuite,然後根據給定的值,就可以得出相應的結果。

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個面的骰子的概率為0(因為4個面的點數只可能為0~4),而6個面的和8個面的概率最大。 現在,假設我們又擲了一次骰子,這次出現的點數是8,重新計算概率:

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

現在可以看到6個面的骰子也被排除了。8個面的骰子是最有可能的。
以上的幾個例子,展示了Counter的用處。實際中,Counter的使用還比較少,如果能夠恰當的使用起來將會帶來非常多的方便。


Tags: 字符串 命名 元素

文章來源:


ads
ads

相關文章
ads

相關文章

ad