欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2016年05月31日 16:55:55   作者:wwt  
Counter是Python標(biāo)準(zhǔn)庫提供的一個(gè)非常有用的容器,可以用來對序列中出現(xiàn)的各個(gè)元素進(jìn)行計(jì)數(shù),下面就來一起看一下Python中Collections模塊的Counter容器類使用教程

1.collections模塊

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

OrderedDict類:排序字典,是字典的子類。引入自2.7。
namedtuple()函數(shù):命名元組,是一個(gè)工廠函數(shù)。引入自2.6。
Counter類:為hashable對象計(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è)無序的容器類型,以字典的鍵值對形式存儲(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

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

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

2.2 計(jì)數(shù)值的訪問與缺失的鍵

當(dāng)所訪問的鍵不存在時(shí),返回0,而不是KeyError;否則返回它的計(jì)數(shù)。

計(jì)數(shù)值的訪問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 計(jì)數(shù)器的更新(update和subtract)

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

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

計(jì)數(shù)器的更新(update)Python

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

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

 
減少則使用subtract()方法:

計(jì)數(shù)器的更新(subtract)Python

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

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

2.4 鍵的刪除

當(dāng)計(jì)數(shù)值為0時(shí),并不意味著元素被刪除,刪除元素應(yīng)當(dāng)使用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()

返回一個(gè)迭代器。元素被重復(fù)了多少次,在該迭代器中就包含多少個(gè)該元素。所有元素按照字母序排序,個(gè)數(shù)小于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])

返回一個(gè)TopN列表。如果n沒有被指定,則返回所有元素。當(dāng)多個(gè)元素計(jì)數(shù)值相同時(shí),按照字母序排列。

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

未實(shí)現(xiàn)的類方法。

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 算術(shù)和集合操作

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

Counter對象的算術(shù)和集合操作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(只保留正數(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

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

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

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

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。

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,簡寫為pmf)是離散隨機(jī)變量在各特定取值上的概率??梢岳肅ounter表示概率質(zhì)量函數(shù)。

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)的組合對,方便畫圖的時(shí)候使用
下面以骰子(ps: 這個(gè)竟然念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,我們可以計(jì)算出兩個(gè)骰子和的分布:

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

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

借助numpy.sum,我們可以直接計(jì)算三個(gè)骰子和的分布:

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

最后可以使用render返回結(jié)果,利用matplotlib把結(jié)果畫圖表示出來:

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é)果如下:

2016531165107908.png (613×458)

4.4貝葉斯統(tǒng)計(jì)
我們繼續(xù)用擲骰子的例子來說明用Counter如何實(shí)現(xiàn)貝葉斯統(tǒng)計(jì)?,F(xiàn)在假設(shè),一個(gè)盒子中有5種不同的骰子,分別是:4面、6面、8面、12面和20面的。假設(shè)我們隨機(jī)從盒子中取出一個(gè)骰子,投出的骰子的點(diǎn)數(shù)為6。那么,取得那5個(gè)不同骰子的概率分別是多少?
(1)首先,我們需要生成每個(gè)骰子的概率質(zhì)量函數(shù):

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)的概率。

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。

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é)果。

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ì)算概率:

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ì)帶來非常多的方便。

相關(guān)文章

  • Python基礎(chǔ)學(xué)習(xí)之認(rèn)識(shí)線程

    Python基礎(chǔ)學(xué)習(xí)之認(rèn)識(shí)線程

    這篇文章主要介紹了Python線程,這篇開始我們將進(jìn)入中級編程。處理更加復(fù)雜事情。比如本文的線程,咱們先從基礎(chǔ)知識(shí)入手,需要的朋友可以參考下下面文章的詳細(xì)內(nèi)容
    2022-02-02
  • 詳解Python中for循環(huán)的使用

    詳解Python中for循環(huán)的使用

    這篇文章主要介紹了Python中for循環(huán)的使用,來自于IBM官方網(wǎng)站技術(shù)文檔,需要的朋友可以參考下
    2015-04-04
  • python manage.py runserver流程解析

    python manage.py runserver流程解析

    這篇文章主要介紹了python manage.py runserver流程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • Python使用pandas實(shí)現(xiàn)對數(shù)據(jù)進(jìn)行特定排序

    Python使用pandas實(shí)現(xiàn)對數(shù)據(jù)進(jìn)行特定排序

    在數(shù)據(jù)分析和處理過程中,排序是一項(xiàng)常見而重要的操作,本文將詳細(xì)介紹如何利用pandas對數(shù)據(jù)進(jìn)行特定排序,包括基本排序、多列排序、自定義排序規(guī)則等方面的內(nèi)容,需要的可以了解下
    2024-03-03
  • Python 類的特殊成員解析

    Python 類的特殊成員解析

    這篇文章主要介紹了Python 類的特殊成員介紹,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2018-06-06
  • Python中使用絕佳的八個(gè)Debug?工具

    Python中使用絕佳的八個(gè)Debug?工具

    在Python開發(fā)中,調(diào)試是解決問題和提高代碼質(zhì)量的關(guān)鍵,有許多強(qiáng)大的調(diào)試工具可幫助開發(fā)者更快速地發(fā)現(xiàn)和解決問題,本文將介紹8個(gè)出色的Python調(diào)試工具,并提供詳細(xì)的示例代碼,讓你更好地了解它們的用法和優(yōu)勢
    2024-01-01
  • Pycharm下載pyinstaller報(bào)錯(cuò):You?should?consider?upgrading?via?the?'python?-m?pip?install?--upgrade?pip'?command的解決方法

    Pycharm下載pyinstaller報(bào)錯(cuò):You?should?consider?upgrading?via

    這篇文章主要給大家介紹了關(guān)于Pycharm下載pyinstaller報(bào)錯(cuò):You?should?consider?upgrading?via?the?'python?-m?pip?install?--upgrade?pip'?command的解決方法,需要的朋友可以參考下
    2022-02-02
  • Python中Django的路由配置詳解

    Python中Django的路由配置詳解

    這篇文章主要介紹了Python中Django的路由配置詳解,Python下有許多款不同的?Web?框架,Django是重量級選手中最有代表性的一位,許多成功的網(wǎng)站和APP都基于Django,需要的朋友可以參考下
    2023-07-07
  • Selenium瀏覽器自動(dòng)化如何上傳文件

    Selenium瀏覽器自動(dòng)化如何上傳文件

    本文主要介紹了Selenium瀏覽器自動(dòng)化如何上傳文件,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-04-04
  • Tensorflow--取tensorf指定列的操作方式

    Tensorflow--取tensorf指定列的操作方式

    這篇文章主要介紹了Tensorflow--取tensorf指定列的操作方式,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06

最新評論