zoukankan      html  css  js  c++  java
  • Collections--Counter

      一个 Counter 是一个 dict 的子类,用于计数可哈希对象。它是一个集合,元素像字典键(key)一样存储,它们的计数存储为值。计数可以是任何整数值,包括0和负数

    元素从一个 iterable 被计数或从其他的 mapping (or counter)初始化:

    >>> c = Counter()                           # a new, empty counter
    >>> c = Counter('gallahad')                 # a new counter from an iterable
    >>> c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
    >>> c = Counter(cats=4, dogs=8)             # a new counter from keyword args
    

      Counter对象有一个字典接口,如果引用的键没有任何记录,就返回一个0,而不是弹出一个 KeyError

    计数器对象除了字典方法以外,还提供了三个其他的方法:

    1. elements()

    返回一个迭代器,每个元素重复计数的个数。元素顺序是任意的。如果一个元素的计数小于1, elements() 就会忽略它。

    >>> c = Counter(a=4, b=2, c=0, d=-2)
    >>> sorted(c.elements())
    ['a', 'a', 'a', 'a', 'b', 'b']
    

      

    2. most_common([n])

    返回一个列表,提供 n 个频率最高的元素和计数。 如果没提供 n ,或者是 None , most_common() 返回计数器中的 所有 元素。相等个数的元素顺序随机:

    >>> Counter('abracadabra').most_common(3)  # doctest: +SKIP
    [('a', 5), ('r', 2), ('b', 2)]
    

      

    3.subtract([iterable-or-mapping])

    从 迭代对象 或 映射对象 减去元素。像 dict.update() 但是是减去,而不是替换。输入和输出都可以是0或者负数。

    >>> c = Counter(a=4, b=2, c=0, d=-2)
    >>> d = Counter(a=1, b=2, c=3, d=4)
    >>> c.subtract(d)
    >>> c
    Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
    

    Counter 对象的常用案例

    sum(c.values())                 # total of all counts
    c.clear()                       # reset all counts
    list(c)                         # list unique elements
    set(c)                          # convert to a set
    dict(c)                         # convert to a regular dictionary
    c.items()                       # convert to a list of (elem, cnt) pairs
    Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs
    c.most_common()[:-n-1:-1]       # n least common elements
    +c                              # remove zero and negative counts
    

      

     典型应用场景

    >>> # 统计一个列表中每个元素重复次数
    >>> cnt = Counter()
    >>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
    ...     cnt[word] += 1
    >>> cnt
    Counter({'blue': 3, 'red': 2, 'green': 1})
    
    >>> # 查找一个文件中出现最频繁的10个字符串
    >>> import re
    >>> words = re.findall(r'w+', open('hamlet.txt').read().lower())
    >>> Counter(words).most_common(10)
    [('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
     ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
    

      

  • 相关阅读:
    【Idea】设置springboot启动环境
    python base64加密解密
    binascii.Error: Incorrect padding
    DataFrame随机采样
    检测和过滤异常值
    离散化和面元划分
    AttributeError: 'Categorical' object has no attribute 'levels'
    AttributeError: 'Categorical' object has no attribute 'labels'
    重命名轴索引
    替换值replace
  • 原文地址:https://www.cnblogs.com/zydev/p/11760239.html
Copyright © 2011-2022 走看看