zoukankan      html  css  js  c++  java
  • Python Counter

    (class)Counter
    Dict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values

    >>> c = Counter('abcdeabcdabcaba')  # count elements from a string
    >>> c.most_common(3)                # three most common elements
    [('a', 5), ('b', 4), ('c', 3)]
    >>> sorted(c)                       # list all unique elements
    ['a', 'b', 'c', 'd', 'e']
    >>> ''.join(sorted(c.elements()))   # list elements with repetitions
    'aaaaabbbbcccdde'
    >>> sum(c.values())                 # total of all counts
    15
    >>> c['a']                          # count of letter 'a'
    5
    >>> for elem in 'shazam':           # update counts from an iterable
    ...     c[elem] += 1                # by adding 1 to each element's count
    >>> c['a']                          # now there are seven 'a'
    7
    >>> del c['b']                      # remove all 'b'
    >>> c['b']                          # now there are zero 'b'
    0
    >>> d = Counter('simsalabim')       # make another counter
    >>> c.update(d)                     # add in the second counter
    >>> c['a']                          # now there are nine 'a'
    9
    >>> c.clear()                       # empty the counter
    >>> c
    Counter()
    Note: If a count is set to zero or reduced to zero, it will remain in the counter until the entry is deleted or the counter is cleared:
    
    >>> c = Counter('aaabbc')
    >>> c['b'] -= 2                     # reduce the count of 'b' by two
    >>> c.most_common()                 # 'b' is still in, but its count is zero
    [('a', 3), ('c', 1), ('b', 0)]
    
  • 相关阅读:
    JSTL 标签库<转>
    EL表达式 <转>
    前端知识点记录
    spring boot 项目连接数据库查询数据过程
    vue -电子时钟
    XML读取
    Druid 连接池
    java JDBC自我总结
    各种数据库的链接方式总结
    Java MD5获取
  • 原文地址:https://www.cnblogs.com/Yuzao/p/15069376.html
Copyright © 2011-2022 走看看