class Counter(dict):
Counter類繼承dict類、繼承了dict的所有功能
計數器:
例:
import collections obj = collections.Counter('sdkasdioasdjoasjdoasd') print(obj)
得:
Counter({'s': 5, 'd': 5, 'a': 4, 'o': 3, 'j': 2, 'k': 1, 'i': 1})
?
拿到前幾位:
""" 數量大于等n的所有元素和計數器 """
def most_common(self, n=None):'''List the n most common elements and their counts from the mostcommon to the least. If n is None, then list all element counts.>>> Counter('abcdeabcdabcaba').most_common(3)[('a', 5), ('b', 4), ('c', 3)]'''# Emulate Bag.sortedByCount from Smalltalkif n is None:return sorted(self.items(), key=_itemgetter(1), reverse=True)return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
例:
import collections obj = collections.Counter('sdkasdioasdjoasjdoasd')
#elements =>> 原生的值
#obj =>> 處理完的數據 print(obj) ret = obj.most_common(4) print(ret)
得:
Counter({'d': 5, 's': 5, 'a': 4, 'o': 3, 'j': 2, 'k': 1, 'i': 1})
[('d', 5), ('s', 5), ('a', 4), ('o', 3)]
?
打印所有的元素、沒有個數
for item in obj.elements():print(item)
?
dict
otems() keys() values()
couter(dic)#繼承了所有字典的方法
otems() keys() values()
“r”:3
elements()#所有的元素
for k,v in obj.items():print(k,v)
?
?
import collections #obj = collections.Counter('sjhdaosdijoasjdoasd') obj = collections.Counter(['11','22','33','22']) print(obj)ret = obj.most_common(4) print(ret)
得:
Counter({'22': 2, '11': 1, '33': 1})
[('22', 2), ('11', 1), ('33', 1)]
?
def update(*args, **kwds):
更新計數器,其實就是增加;如果原來沒有,則新建,如果有則加一'''Like dict.update() but add counts instead of replacing them.Source can be an iterable, a dictionary, or another Counter instance.>>> c = Counter('which')>>> c.update('witch') # add elements from another iterable>>> d = Counter('watch')>>> c.update(d) # add elements from another counter>>> c['h'] # four 'h' in which, witch, and watch4'''# The regular dict.update() operation makes no sense here because the# replace behavior results in the some of original untouched counts# being mixed-in with all of the other counts for a mismash that# doesn't have a straight-forward interpretation in most counting# contexts. Instead, we implement straight-addition. Both the inputs# and outputs are allowed to contain zero and negative counts.if not args:raise TypeError("descriptor 'update' of 'Counter' object ""needs an argument")self, *args = argsif len(args) > 1:raise TypeError('expected at most 1 arguments, got %d' % len(args))iterable = args[0] if args else Noneif iterable is not None:if isinstance(iterable, Mapping):if self:self_get = self.getfor elem, count in iterable.items():self[elem] = count + self_get(elem, 0)else:super(Counter, self).update(iterable) # fast path when counter is emptyelse:_count_elements(self, iterable)if kwds:self.update(kwds)
例(增加):
import collections obj = collections.Counter(['11','22','33','22']) print(obj)obj.update(['eric','11','11'])#增加 print(obj)
得:
Counter({'22': 2, '11': 1, '33': 1})
Counter({'11': 3, '22': 2, '33': 1, 'eric': 1})
?
例(減去):
import collections obj = collections.Counter(['11','22','33','22']) print(obj) obj.subtract(['eric','11','11'])#刪除 print(obj)
得:
Counter({'22': 2, '11': 1, '33': 1})
Counter({'22': 2, '33': 1, '11': -1, 'eric': -1})
?