collections系列

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 most
        common 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 Smalltalk
        if 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 watch 4 ''' # 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 = args if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) iterable = args[0] if args else None if iterable is not None: if isinstance(iterable, Mapping): if self: self_get = self.get for elem, count in iterable.items(): self[elem] = count + self_get(elem, 0) else: super(Counter, self).update(iterable) # fast path when counter is empty else: _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})





原文地址:https://www.cnblogs.com/mrzuo/p/7094911.html