개발/Python

[Python] - Counter

Dortmoot 2022. 7. 27. 20:24

Counter


  • A Counter is a dict subclass for counting hashable objects.
  • collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

Syntax

Counter([iterable-or-mapping])
from collections import Counter

c = Counter('gallahad')
> Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1})

c = Counter({'red': 4, 'blue': 2})
> Counter({'red': 4, 'blue': 2})

c = Counter(cats=4, dogs=8) 
> Counter({'dogs': 8, 'cats': 4})

 

elements()

  • Return an iterator over elements repeating each as many times as its count.
  • If an element’s count is less than one, ignore
c = Counter({'red': 4, 'blue': 2})
list(c.elements())
> ['red', 'red', 'red', 'red', 'blue', 'blue']

most_common(n)

  • Return a list of the n most common elements
  • If n None, returns all elements in the counter
Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]

subtract([iterable-or-mapping])

  • Elements are subtracted from an iterable or from another mapping (or counter)
c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
c.subtract(d)
> Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

total()

  • Compute the sum of the counts.
c = Counter(a=10, b=5, c=0)
c.total()
> 15