Python 中的計數器?


計數器是一個容器,它跟蹤添加了多少個等效值。Python 計數器類是 collections 模組的一部分,並且是字典的子類。

Python 計數器

我們可以將計數器視為專案的無序集合,其中專案儲存為字典鍵,它們的計數儲存為字典值。

計數器專案的計數可以是正整數、零或負整數。雖然對它的鍵和值沒有限制,但通常值應為數字,但我們也可以儲存其他物件型別。

初始化

計數器支援三種初始化形式。它的建構函式可以用一系列專案、包含鍵和計數的字典或使用將字串名稱對映到計數的關鍵字引數來呼叫。

import collections
print (collections.Counter(['a', 'b', 'c', 'a', 'b', 'b']))
print (collections.Counter({'a': 2, 'b': 3, 'c':1}))
print(collections.Counter(a=2, b=3, c=1))

所有三種初始化形式的輸出相同:

Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})

要建立一個空計數器,請傳遞不帶引數的計數器,並透過 update 方法填充它。

import collections
c = collections.Counter()
print('Initial: ', c)
c.update('abcddcba')
print('Sequence: ', c)
c.update({'a': 1, 'd':5})
print('Dict: ', c)

輸出

Initial: Counter()
Sequence: Counter({'a': 2, 'b': 2, 'c': 2, 'd': 2})
Dict: Counter({'d': 7, 'a': 3, 'b': 2, 'c': 2})

訪問計數

填充計數器後,可以透過字典 API 獲取其值。

import collections
c = collections.Counter('abcddcba')
for letter in 'abcdef':
   print('%s : %d' %(letter, c[letter]))

輸出

a : 2
b : 2
c : 2
d : 2
e : 0
f : 0

對於未知項(例如,我們在上述程式中提到的 e & f 項),計數器不會引發 KeyError。如果輸入中未看到某個值,則其計數為 0(例如,上述輸出中未知項 e & f 的計數)。

elements() 方法返回一個迭代器,該迭代器生成計數器已知的全部專案。

import collections
c = collections.Counter('Python Counters')
c['z'] = 0
print(c)
print(list(c.elements()))

輸出

Counter({'t': 2, 'o': 2, 'n': 2, 'P': 1, 'y': 1, 'h': 1, ' ': 1, 'C': 1, 'u': 1, 'e': 1, 'r': 1, 's': 1, 'z': 0})
['P', 'y', 't', 't', 'h', 'o', 'o', 'n', 'n', ' ', 'C', 'u', 'e', 'r', 's']

元素的順序不固定,並且計數小於零的專案不包括在內。

要從 n 個輸入及其各自的計數中生成常用輸入,我們使用 most_common() 函式。

import collections
c = collections.Counter()
texts = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa
qui officia deserunt mollit anim id est laborum.'''
for word in texts:
c.update(word.rstrip().lower())
print("Five most common letters in the texts: ")
for letter, count in c.most_common(5):
print("%s: %7d" %(letter, count))

輸出

Five most common letters in the texts:
i: 42
e: 38
t: 32
o: 29
u: 29

上面的示例計算文字(或您可以考慮檔案)中出現的字母以生成頻率分佈,然後列印五個最常見的字母。省略 most_common() 的引數會生成所有專案的列表,按頻率排序。

算術運算

計數器例項支援算術運算和集合運算以聚合結果。

import collections
c1 = collections.Counter(['a', 'b', 'c', 'a' ,'b', 'b'])
c2 = collections.Counter('alphabet')
print('C1: ', c1)
print('C2: ', c2)
print ('\nCombined counts: ')
print(c1 + c2)
print('\nSubtraction: ')
print(c1 - c2)
print('\nIntersection (taking positive minimums): ')
print(c1 & c2)
print('\nUnion (taking maximums): ')
print(c1 | c2)

輸出

C1: Counter({'b': 3, 'a': 2, 'c': 1})
C2: Counter({'a': 2, 'l': 1, 'p': 1, 'h': 1, 'b': 1, 'e': 1, 't': 1})
Combined counts:
Counter({'a': 4, 'b': 4, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})
Subtraction:
Counter({'b': 2, 'c': 1})
Intersection (taking positive minimums):
Counter({'a': 2, 'b': 1})
Union (taking maximums):
Counter({'b': 3, 'a': 2, 'c': 1, 'l': 1, 'p': 1, 'h': 1, 'e': 1, 't': 1})

每次透過運算產生新的計數器時,任何計數為零或負的項都會被丟棄。

更新於:2019年7月30日

3K+ 瀏覽量

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.