最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

1.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。

2.Counter類

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

2.1 創(chuàng)建

下面的代碼說明了Counter類創(chuàng)建的四種方法:

Counter類的創(chuàng)建Python

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

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

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

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

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

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

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

計數(shù)器的更新(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()方法:

計數(shù)器的更新(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 鍵的刪除

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

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

返回一個TopN列表。如果n沒有被指定,則返回所有元素。當(dāng)多個元素計數(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

未實現(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。其中&和|操作分別返回兩個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ù)計數(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ù)計數(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()) # 所有計數(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] # 取出計數(shù)最少的n個元素
c += Counter() # 移除0和負(fù)值

sum(c.values()) # 所有計數(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] # 取出計數(shù)最少的n個元素
c += Counter() # 移除0和負(fù)值

4.實例
4.1判斷兩個字符串是否由相同的字母集合調(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ù)是字符串,就會統(tǒng)計字符串中每個字符出現(xiàn)的次數(shù),如果兩個字符串由相同的字母集合顛倒順序而成,則它們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: 返回的是兩個隨機(jī)變量分布兩兩組合之和的新的概率質(zhì)量函數(shù)
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返回結(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)計
我們繼續(xù)用擲骰子的例子來說明用Counter如何實現(xiàn)貝葉斯統(tǒng)計?,F(xiàn)在假設(shè),一個盒子中有5種不同的骰子,分別是:4面、6面、8面、12面和20面的。假設(shè)我們隨機(jī)從盒子中取出一個骰子,投出的骰子的點數(shù)為6。那么,取得那5個不同骰子的概率分別是多少?
(1)首先,我們需要生成每個骰子的概率質(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)接下來,定義一個抽象類Suite。Suite是一個概率質(zhì)量函數(shù)表示了一組假設(shè)(hypotheses)及其概率分布。Suite類包含一個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ù)由各個類繼承后,自己實現(xiàn)不同的計算方法。

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

并且實現(xiàn)了likelihood函數(shù),其中傳入的兩個參數(shù)為: data: 觀察到的骰子擲出的點數(shù),如本例中的6 hypo: 可能擲出的那個骰子

(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個面的骰子的概率為0(因為4個面的點數(shù)只可能為0~4),而6個面的和8個面的概率最大。 現(xiàn)在,假設(shè)我們又?jǐn)S了一次骰子,這次出現(xiàn)的點數(shù)是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

現(xiàn)在可以看到6個面的骰子也被排除了。8個面的骰子是最有可能的。
以上的幾個例子,展示了Counter的用處。實際中,Counter的使用還比較少,如果能夠恰當(dāng)?shù)氖褂闷饋韺矸浅6嗟姆奖恪?br />

相關(guān)文章

  • Django用戶認(rèn)證系統(tǒng) 組與權(quán)限解析

    Django用戶認(rèn)證系統(tǒng) 組與權(quán)限解析

    這篇文章主要介紹了Django用戶認(rèn)證系統(tǒng) 組與權(quán)限解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-08-08
  • Python+SQLAlchemy輕松實現(xiàn)管理數(shù)據(jù)庫

    Python+SQLAlchemy輕松實現(xiàn)管理數(shù)據(jù)庫

    QLAlchemy是一個強(qiáng)大的ORM(對象關(guān)系映射)庫,它允許您通過Python代碼與關(guān)系型數(shù)據(jù)庫進(jìn)行交互,本文我們將學(xué)習(xí)如何使用Python和SQLAlchemy庫來輕松管理數(shù)據(jù)庫,需要的可以參考下
    2023-05-05
  • Python?matplotlib?繪制散點圖詳解建議收藏

    Python?matplotlib?繪制散點圖詳解建議收藏

    在數(shù)據(jù)統(tǒng)計圖表中,有一種圖表是散列點分布在坐標(biāo)中,反應(yīng)數(shù)據(jù)隨著自變量變化的趨勢。這篇文章主要介紹了如何通過matplotlib繪制散點圖,需要的朋友可以參考一下
    2021-12-12
  • Python 私有化操作實例分析

    Python 私有化操作實例分析

    這篇文章主要介紹了Python 私有化操作,結(jié)合實例形式分析了Python私有屬性、私有方法相關(guān)使用技巧,需要的朋友可以參考下
    2019-11-11
  • Python字符串切片操作知識詳解

    Python字符串切片操作知識詳解

    這篇文章主要介紹了Python中字符串切片操作 的相關(guān)資料,需要的朋友可以參考下
    2016-03-03
  • 使用python實現(xiàn)kmean算法

    使用python實現(xiàn)kmean算法

    這篇文章主要介紹了使用python實現(xiàn)kmean算法,kmean 是無監(jiān)督學(xué)習(xí)的一種算法,主要是用來進(jìn)行聚類分析的,他會在數(shù)據(jù)集中算出幾個點作為簇中心,求這些數(shù)據(jù)集與這些簇中心的距離,并將距離同一個簇中心距離最近的數(shù)據(jù)歸為一類,需要的朋友可以參考下
    2023-04-04
  • Python協(xié)程環(huán)境下文件操作的正確方法

    Python協(xié)程環(huán)境下文件操作的正確方法

    在Python協(xié)程中執(zhí)行文件操作是常見的需求,但直接使用同步文件讀寫會阻塞事件循環(huán),破壞異步并發(fā)優(yōu)勢,本文將深入解析協(xié)程環(huán)境下文件操作的正確方法,涵蓋多種場景下的最佳實踐和性能優(yōu)化技巧,需要的朋友可以參考下
    2025-09-09
  • 解決python通過cx_Oracle模塊連接Oracle亂碼的問題

    解決python通過cx_Oracle模塊連接Oracle亂碼的問題

    今天小編就為大家分享一篇解決python通過cx_Oracle模塊連接Oracle亂碼的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-10-10
  • Python音頻處理庫pydub的使用示例詳解

    Python音頻處理庫pydub的使用示例詳解

    pydub是一個輕量級的音頻處理庫,安裝方便,使用簡單,這篇文章主要為大家詳細(xì)介紹了pydub的具體使用,文中的示例代碼講解詳細(xì),需要的小伙伴可以參考下
    2023-11-11
  • 使用Python實現(xiàn)簡單的學(xué)生成績管理系統(tǒng)

    使用Python實現(xiàn)簡單的學(xué)生成績管理系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了Python實現(xiàn)學(xué)生成績管理系統(tǒng),使用數(shù)據(jù)庫,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-01-01

最新評論

泌阳县| 湖州市| 澳门| 天全县| 微博| 凤山市| 信宜市| 庄河市| 镇沅| 夏津县| 米泉市| 周宁县| 桦川县| 河池市| 安西县| 舒城县| 新津县| 思茅市| 荥经县| 渝北区| 南华县| 琼海市| 珠海市| 香格里拉县| 潢川县| 姜堰市| 沙河市| 玛多县| 乌什县| 揭西县| 涟源市| 象山县| 本溪| 雷山县| 锦州市| 越西县| 建昌县| 小金县| 林甸县| 县级市| 武川县|