這是一個統(tǒng)計一個序列中元素出現(xiàn)的次數(shù)的內(nèi)置庫。
統(tǒng)計字符串
如果我們有這樣一個字符串州叠。我們要統(tǒng)計字符串中每個字符出現(xiàn)的次數(shù)放闺,可以使用Counter類來輕松搞定。
my_str = "hello world. python is the best."
from collections import Counter
s = "hello world. python is the best."
c = Counter(s)
print(c)
輸出如下:
然后我們可以方便的做進一步處理。比如蒂誉,統(tǒng)計's' 't' 'a' 'c' 'k'所有字符總共出現(xiàn)了幾次教藻?
from collections import Counter
s = "hello world. python is the best."
c = Counter(s)
total = sum([v for k, v in c.items() if k in ['s', 't', 'a', 'c', 'k']])
print(total)
思路:遍歷Counter對象c,我們可以簡單認(rèn)為c是一個dict右锨,使用items()方法可以遍歷dict的key和value括堤。
如果key是’stack‘這五個字符中的任意一個,則把value作為一個列表元素返回到列表绍移。
最后調(diào)用sum()函數(shù)悄窃,對列表生成式進行求和。
接下來試試list
再比如蹂窖,我們現(xiàn)在有一個名字列表轧抗,我們要統(tǒng)計每個名字出現(xiàn)的次數(shù)。
from collections import Counter
elements = ['jack', 'JACK', 'lucy', 'April', 'Lucy', 'mike', 'JAck']
c = Counter(elements)
print(c)
輸出如下圖:
Counter類的特性
通過前面的例子恼策,你也許已經(jīng)猜到了鸦致,Counter()的構(gòu)造函數(shù)接受一個序列(str, list, tuple, set)作為參數(shù)潮剪。
可以使用counter.update()更新counter
from collections import Counter
elements = ['jack', 'JACK', 'lucy', 'April', 'Lucy', 'mike', 'JAck']
c = Counter(elements)
print(c)
new_elements = ['alice', 'steven']
c.update(new_elements)
print(c)
- 可以使用counter.subtract()函數(shù)減少counter
from collections import Counter
elements = ['jack', 'JACK', 'lucy', 'April', 'Lucy', 'mike', 'JAck']
c = Counter(elements)
print(c)
new_elements = ['alice', 'steven', 'jack']
c.subtract(new_elements)
print(c)
通過結(jié)果涣楷,我們發(fā)現(xiàn)如果new_elements中的元素如果存在會被減1,如果原來的list中沒有這個元素抗碰,這個元素會被記為-1.
- 我們還可以刪除要統(tǒng)計的元素狮斗,使用del關(guān)鍵字
del c['jack']
- 遍歷counter中的所有元素,使用counter.elements()函數(shù)弧蝇。
值得注意的是:elements()函數(shù)會返回一個迭代器碳褒,這個迭代器中包含了所有的key逛薇,如果這個key對應(yīng)的value小于1荒给,則不會被elements()函數(shù)計算在內(nèi)。
還可以調(diào)用counter.most_common([n])函數(shù)锹杈,獲取數(shù)量最多的前n個元素两芳。
其中n是可選參數(shù)摔寨,如果n沒有被指定,那么返回所有元素怖辆。更牛逼的是是复,這個counter還支持集合操作。 +, -, &, |.
from collections import Counter
a = Counter('aaab')
b = Counter('ccdd')
# +
a_sum_b = a + b
print(a_sum_b)
# -
a_sub_b = a - b
print(a_sub_b)
# &竖螃, 交集
a_and_b = a & b
print(a_and_b)
# |淑廊, 并集
a_union_b = a | b
print(a_union_b)