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.
    
    
  • 相关阅读:
    MySQL_基础_TCL事务控制语言
    MySQL_基础_DDL数据定义语言
    MySQL_基础_DQL数据查询语言
    MySQL_基础_DML数据操纵语言
    MySQL_基础_存储过程和函数
    MySQL_基础_变量
    linux 常用命令
    灵活QinQ示例
    RRPP 演示实例
    ERPS实例演示
  • 原文地址:https://www.cnblogs.com/songdanzju/p/7441683.html
Copyright © 2011-2022 走看看