引言
計數是在數據處理過程中非常常見的任務。常見的例子包括:統計單詞頻率,統計字母出現次數等。然而在Python中,為了實現這些任務,需要編寫相對複雜的代碼,並且效率較低。針對這一問題,Python提供了collections模塊中的Counter類,用以簡化計數任務並提升代碼的效率。
一、Counter類的介紹
1. Counter類的基本使用方法
from collections import Counter c = Counter('abcdeabcdabcaba') print(c)
輸出:
Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
Counter類接受一個可迭代對象,並統計其中元素出現的次數,最終返回一個字典,其中鍵為元素,值為元素出現的次數。
2. 操作Counter對象
Counter對象除了可以直接輸出元素的計數結果,還支持一系列的操作函數,例如most_common, elements等,下面說一下幾個常用的操作函數:
(1)most_common
most_common方法返回一個由計數值從高到低排列的元素列表。
c = Counter('abcdeabcdabcaba') print(c.most_common(3))
輸出:
[('a', 5), ('b', 4), ('c', 3)]
(2)elements
elements方法返回一個迭代器,包含每個元素在Counter對象中出現的次數個重複元素。
c = Counter('abcdeabcdabcaba') print(list(c.elements()))
輸出:
['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']
(3)update
update方法將 Counter 實例於另一個可迭代對象相加。
c1 = Counter('abcdeabcdabcaba') c2 = Counter('abc') c1.update(c2) print(c1)
輸出:
Counter({'a': 6, 'b': 5, 'c': 4, 'd': 2, 'e': 1})
二、collections.Counter類的優勢
1. 減少代碼量
Counter類的出現,減少了我們進行計數的代碼量,同時也提高了代碼的可讀性和可維護性。下面給出一個比較常見的計數樣例:
a = 'This is a sample sentence comprising of different words. A sentence is a symbolic representation of the language and grammar' d = {} for word in a.split(): if word in d: d[word] += 1 else: d[word] = 1 print(d)
Counter的實現:
from collections import Counter a = 'This is a sample sentence comprising of different words. A sentence is a symbolic representation of the language and grammar' d = Counter(a.split()) print(d)
僅需要幾行代碼就能夠完成同樣的任務。
2. 提高計數效率
Collections模塊中的Counter類是通過 C 語言的擴展模塊實現的。相比於普通的Python方法,它的計數效率要高出許多。下面是兩個簡單的實驗示例,可用於佐證上述觀點:
import time from collections import Counter start_time = time.time() a = 'This is a sample sentence comprising of different words. A sentence is a symbolic representation of the language and grammar' d = {} for word in a.split(): if word in d: d[word] += 1 else: d[word] = 1 end_time = time.time() print("方法一用時:{}s".format(end_time - start_time)) start_time = time.time() d = Counter(a.split()) end_time = time.time() print("方法二用時:{}s".format(end_time - start_time))
輸出效果如下:
方法一用時:1.3828279972076416e-05s 方法二用時:1.8835067749023438e-05s
可以看到,使用Counter類比手寫代碼運算速度快了一些。這一點,在處理大規模數據時,就更加明顯了。
三、總結
Python中的collections模塊提供了許多可以簡化代碼的數據結構,其中的Counter類向我們展示了計數是多麼容易。在進行計數任務時,推薦使用Counter類,它既能夠減少代碼的工作量,又能夠提高效率。
原創文章,作者:NYUQ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/135804.html