Python計数モジュールCounter

4691 ワード

Pythonに内蔵されたCounterモジュールは、特にオブジェクトの個数を計算するのに便利です
  • まず、このモジュールに対するソースコードの説明
  • を見てみましょう.
    class Counter(dict):
        '''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.
    

    辞書のサブクラスは、hashtableを計算するために使用され、袋または複数のタイプの辞書と呼ばれることがある.要素は辞書のキーとして、要素の数は辞書の値として使用されます.
       >>> 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)]
    
  • 一般的な方法は辞書を持つアクセス方法を紹介し、cは辞書のサブクラスであるため、辞書のアクセス削除などの方法
  • を継承する.
    >>> c = Counter('abcdeabcdabcaba') 
    >>>  c.items()
    dict_items([('b', 4), ('c', 3), ('a', 5), ('d', 2), ('e', 1)])
    >>> c['a']
    5
    >>> c.get("a")
    5
    >>> c.keys()
    dict_keys(['b', 'c', 'a', 'd', 'e'])
    >>> c.values()
    dict_values([4, 3, 5, 2, 1])
    >>> c.pop("a")
    5
    >>> c.clear()
    
    
  • Counterクラス独自の方法
  • >>> c.most_common(3) #       
    [('b', 4), ('c', 3), ('d', 2)]
    >>> c
     Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
    >>> c.update("abc")  #        c 
    >>> c
    Counter({'a': 6, 'b': 5, 'c': 4, 'd': 2, 'e': 1})
    >>> d = Counter("abc")
    >>> c.update(d) #     counter   
    >>> c
    Counter({'a': 7, 'b': 6, 'c': 5, 'd': 2, 'e': 1})
    >>> c.clear()
    >>> c
    Counter()
    
    # Counter         
    >>> c = Counter(a=3, b=1, c=5)
    >>> d = Counter(a=1, b=2, d=4)
    >>> c + d                       # counter  ,    key value  
    Counter({'c': 5, 'a': 4, 'd': 4, 'b': 3})
    >>> c - d                       # counter  ,    key value  ,      value
    Counter({'c': 5, 'a': 2})
    >>> c & d                       #   :        key,value      
    Counter({'a': 1, 'b': 1})
    >>> c | d                       #   :       key, key      ,   value
    Counter({'c': 5, 'd': 4, 'a': 3, 'b': 2})
        :
    sum(c.values())                 #       .values()    values   ,   
    c.clear()                       #       .clear()  ,  counter
    list(c)                         #   key   list
    set(c)                          #   key   set
    dict(c)                         #      
    c.items()                       #    (  ,   )     
    Counter(dict(list_of_pairs))    #  (  ,   )        Counter
    c.most_common()[:-n-1:-1]       #   n    (  ,   )     
    
    

    説明:Counterは辞書のmissingメソッドを実現しているため、存在しないkeyにアクセスした場合、戻り値は0になります.