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.
    
    
  • 相关阅读:
    C# 重载,重写,代理,枚举实例
    关于C#7 新语法糖
    关于C# 异步
    经验
    C# 后台模块 Word 模板操作
    .Net 图片生成水印
    .Net XML操作
    .Net web 关于表单标题
    分页存储过程
    python 爬虫 猫眼视频榜单top100
  • 原文地址:https://www.cnblogs.com/songdanzju/p/7441683.html
Copyright © 2011-2022 走看看