zoukankan      html  css  js  c++  java
  • Python Counter class

    Counter class

    https://docs.python.org/2/library/collections.html#collections.Counter

    # class collections.Counter([iterable-or-mapping])
    # A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.
    
    >>> # Tally occurrences of words in a list
    >>> cnt = Counter()
    >>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
    ...     cnt[word] += 1
    >>> cnt
    Counter({'blue': 3, 'red': 2, 'green': 1})
    
    >>> # Find the ten most common words in Hamlet
    >>> 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)]
     
    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 += Counter()                  # remove zero and negative counts
    
    # most_common([n])
    # Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter.
    
    
  • 相关阅读:
    安装黑苹果的config.plist
    navicat for mysql 导出数据的坑
    js中的深层复制
    js写的一个HashMap
    js前台数据校验
    nginx对上传文件大小的限制
    tomcat用户配置,内存配置,pid配置
    redis安装及使用
    程序端口被占用分析
    zookeeper+dubbo-admin开发dubbo应用
  • 原文地址:https://www.cnblogs.com/songdanzju/p/7441683.html
Copyright © 2011-2022 走看看