zoukankan      html  css  js  c++  java
  • python之collections之counter

    一、定义

    Counter(计数器)是对字典的补充,用于追踪值的出现次数。

    Counter是一个继承了字典的类(Counter(dict))

    二、相关方法

    继承了字典的类,有关字典的相关方法也一并继承过来。

    比如items()方法

    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))
    eg:



    def elements(self):
    '''
      显示计数器中所有的元素
      Iterator over elements repeating each as many times as its count.

    >>> c = Counter('ABCABC')
    >>> sorted(c.elements())
    ['A', 'A', 'B', 'B', 'C', 'C']

    # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
    >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
    >>> product = 1
    >>> for factor in prime_factors.elements(): # loop over factors
    ... product *= factor # and multiply them
    >>> product
    1836

    Note, if an element's count has been set to zero or is a negative
    number, elements() will ignore it.

    '''
    # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
    return _chain.from_iterable(_starmap(_repeat, self.items()))

    # Override dict methods where necessary
    eg:



    @classmethod
    def fromkeys(cls, iterable, v=None):
    # There is no equivalent method for counters because setting v=1
    # means that no element can have a count greater than one.
    此功能没有实现
    raise NotImplementedError(
    'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')

    def update(*args, **kwds):
    '''
      更新Counter,对于已有的元素计数加一,对没有的元素进行添加
      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)
    eg:


    def subtract(*args, **kwds):
    '''Like dict.update() but subtracts counts instead of replacing them.
    Counts can be reduced below zero. Both the inputs and outputs are
    allowed to contain zero and negative counts.

    Source can be an iterable, a dictionary, or another Counter instance.

    >>> c = Counter('which')
    >>> c.subtract('witch') # subtract elements from another iterable
    >>> c.subtract(Counter('watch')) # subtract elements from another counter
    >>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch
    0
    >>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch
    -1
      对指定的Counter元素做减法运算,对出现过的累计减一(可以出现负数),对没有出现过的进行0-1运算
    '''
    if not args:
    raise TypeError("descriptor 'subtract' 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:
    self_get = self.get
    if isinstance(iterable, Mapping):
    for elem, count in iterable.items():
    self[elem] = self_get(elem, 0) - count
    else:
    for elem in iterable:
    self[elem] = self_get(elem, 0) - 1
    if kwds:
    self.subtract(kwds)
    eg:


    def copy(self):
    'Return a shallow copy.'
    return self.__class__(self)
      Counter的浅拷贝
  • 相关阅读:
    centos8网络连接(1)虚拟机网卡和网络编辑器设置
    centos7离线安装ruby
    centos7安装ruby-2.6.5,简单快捷的下载与安装方式
    redis 4.0.13 -- 集群模式
    活了
    世界无我
    markdown_test
    关于mimikatz在webshell运行
    可用性自动化V3
    关于sqlmap常用
  • 原文地址:https://www.cnblogs.com/baotouzhangce/p/6179911.html
Copyright © 2011-2022 走看看