一、計數器(counter)
Counter是對字典類型的補充,用於追蹤值的出現次數。
具備字典的所有功能 + 自己的功能。
1 import collections 2 aa = collections.Counter("sdfdsgsdf;sdfssfd") #把所有元素出現的次數統計下來了 3 print(aa) 4 5 輸出結果: 6 Counter({'s': 6, 'd': 5, 'f': 4, ';': 1, 'g': 1})
部分源碼分析:
1 def most_common(self, n=None): 2 '''List the n most common elements and their counts from the most 3 common to the least. If n is None, then list all element counts. 4
5 >>> Counter('abcdeabcdabcaba').most_common(3) 6 [('a', 5), ('b', 4), ('c', 3)] 7
8 '''
9 # Emulate Bag.sortedByCount from Smalltalk
10 if n is None: 11 return sorted(self.items(), key=_itemgetter(1), reverse=True) 12 return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
1 #獲取元素出現次數多的幾個 2 bb = aa.most_common(3) #取元素次數最多的前3個 3 print(bb) 4 5 #執行結果: 6 [('s', 6), ('d', 5), ('f', 4)]
1 def elements(self): 2 '''Iterator over elements repeating each as many times as its count. 3
4 >>> c = Counter('ABCABC') 5 >>> sorted(c.elements()) 6 ['A', 'A', 'B', 'B', 'C', 'C'] 7
8 # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 9 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) 10 >>> product = 1 11 >>> for factor in prime_factors.elements(): # loop over factors 12 ... product *= factor # and multiply them 13 >>> product 14 1836 15
16 Note, if an element's count has been set to zero or is a negative 17 number, elements() will ignore it. 18
19 '''
20 # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
21 return _chain.from_iterable(_starmap(_repeat, self.items())) 22
23 # Override dict methods where necessary
1 #其他輸出方式 2 for item in aa.elements(): #迭代輸出元素(同一元素出現幾次,就連續輸出該元素幾次),無序 3 print(item) 4 5 for k,v in aa.items(): #把所有元素拿出來,再統計該元素出現次數 6 print(k,v) 7 8 #執行結果: 9 ; 10 s 11 s 12 s 13 s 14 s 15 s 16 f 17 f 18 f 19 f 20 d 21 d 22 d 23 d 24 d 25 g 26 ; 1 27 s 6 28 f 4 29 d 5 30 g 1
counter和elements的區別:elements處理的是原生的值;而counter處理的是已經處理完的數據
1 def update(*args, **kwds): 2 '''Like dict.update() but add counts instead of replacing them. 3
4 Source can be an iterable, a dictionary, or another Counter instance.
1 #更新計數器, 2 import collections 3 aa = collections.Counter(["11","22","33","22"]) #把所有元素出現的次數統計下來了 4 print(aa) 5 aa.update(["ggg","11","11"]) 6 print(aa) 7 8 #執行結果: 9 Counter({'22': 2, '33': 1, '11': 1}) 10 Counter({'11': 3, '22': 2, 'ggg': 1, '33': 1})
1 def subtract(*args, **kwds): 2 '''Like dict.update() but subtracts counts instead of replacing them. 3 Counts can be reduced below zero. Both the inputs and outputs are 4 allowed to contain zero and negative counts. 5
6 Source can be an iterable, a dictionary, or another Counter instance.
1 #減少元素 2 import collections 3 aa = collections.Counter(["11","22","33","22"]) #把所有元素出現的次數統計下來了 4 print(aa) 5 aa.subtract(["ggg","11","11"]) #如果不存在,也減 6 print(aa) 7 8 #執行結果: 9 Counter({'22': 2, '11': 1, '33': 1}) 10 Counter({'22': 2, '33': 1, 'ggg': -1, '11': -1})