Back to index

python3.2  3.2.2
Public Member Functions
collections.Counter Class Reference

List of all members.

Public Member Functions

def __init__
def __missing__
def most_common
def elements
def fromkeys
def update
def subtract
def copy
def __reduce__
def __delitem__
def __repr__
def __add__
def __sub__
def __or__
def __and__

Detailed Description

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.

>>> 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)]

Definition at line 397 of file collections.py.


Constructor & Destructor Documentation

def collections.Counter.__init__ (   self,
  iterable = None,
  kwds 
)
Create a new, empty Counter object.  And if given, count elements
from an input iterable.  Or, initialize the count from another mapping
of elements to their counts.

>>> c = Counter()                           # a new, empty counter
>>> c = Counter('gallahad')                 # a new counter from an iterable
>>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping
>>> c = Counter(a=4, b=2)                   # a new counter from keyword args

Definition at line 448 of file collections.py.

00448 
00449     def __init__(self, iterable=None, **kwds):
00450         '''Create a new, empty Counter object.  And if given, count elements
00451         from an input iterable.  Or, initialize the count from another mapping
00452         of elements to their counts.
00453 
00454         >>> c = Counter()                           # a new, empty counter
00455         >>> c = Counter('gallahad')                 # a new counter from an iterable
00456         >>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping
00457         >>> c = Counter(a=4, b=2)                   # a new counter from keyword args
00458 
00459         '''
00460         super().__init__()
00461         self.update(iterable, **kwds)

Here is the call graph for this function:

Here is the caller graph for this function:


Member Function Documentation

def collections.Counter.__add__ (   self,
  other 
)
Add counts from two counters.

>>> Counter('abbb') + Counter('bcc')
Counter({'b': 4, 'c': 2, 'a': 1})

Definition at line 598 of file collections.py.

00598 
00599     def __add__(self, other):
00600         '''Add counts from two counters.
00601 
00602         >>> Counter('abbb') + Counter('bcc')
00603         Counter({'b': 4, 'c': 2, 'a': 1})
00604 
00605         '''
00606         if not isinstance(other, Counter):
00607             return NotImplemented
00608         result = Counter()
00609         for elem, count in self.items():
00610             newcount = count + other[elem]
00611             if newcount > 0:
00612                 result[elem] = newcount
00613         for elem, count in other.items():
00614             if elem not in self and count > 0:
00615                 result[elem] = count
00616         return result

Here is the call graph for this function:

Here is the caller graph for this function:

def collections.Counter.__and__ (   self,
  other 
)
Intersection is the minimum of corresponding counts.

>>> Counter('abbb') & Counter('bcc')
Counter({'b': 1})

Definition at line 656 of file collections.py.

00656 
00657     def __and__(self, other):
00658         ''' Intersection is the minimum of corresponding counts.
00659 
00660         >>> Counter('abbb') & Counter('bcc')
00661         Counter({'b': 1})
00662 
00663         '''
00664         if not isinstance(other, Counter):
00665             return NotImplemented
00666         result = Counter()
00667         for elem, count in self.items():
00668             other_count = other[elem]
00669             newcount = count if count < other_count else other_count
00670             if newcount > 0:
00671                 result[elem] = newcount
00672         return result
00673 

Here is the call graph for this function:

def collections.Counter.__delitem__ (   self,
  elem 
)

Definition at line 578 of file collections.py.

00578 
00579     def __delitem__(self, elem):
00580         'Like dict.__delitem__() but does not raise KeyError for missing values.'
00581         if elem in self:
00582             super().__delitem__(elem)

def collections.Counter.__missing__ (   self,
  key 
)

Definition at line 462 of file collections.py.

00462 
00463     def __missing__(self, key):
00464         'The count of elements not in the Counter is zero.'
00465         # Needed so that self[missing_item] does not raise KeyError
00466         return 0

Here is the caller graph for this function:

def collections.Counter.__or__ (   self,
  other 
)
Union is the maximum of value in either of the input counters.

>>> Counter('abbb') | Counter('bcc')
Counter({'b': 3, 'c': 2, 'a': 1})

Definition at line 636 of file collections.py.

00636 
00637     def __or__(self, other):
00638         '''Union is the maximum of value in either of the input counters.
00639 
00640         >>> Counter('abbb') | Counter('bcc')
00641         Counter({'b': 3, 'c': 2, 'a': 1})
00642 
00643         '''
00644         if not isinstance(other, Counter):
00645             return NotImplemented
00646         result = Counter()
00647         for elem, count in self.items():
00648             other_count = other[elem]
00649             newcount = other_count if count < other_count else count
00650             if newcount > 0:
00651                 result[elem] = newcount
00652         for elem, count in other.items():
00653             if elem not in self and count > 0:
00654                 result[elem] = count
00655         return result

Here is the call graph for this function:

Definition at line 575 of file collections.py.

00575 
00576     def __reduce__(self):
00577         return self.__class__, (dict(self),)

Definition at line 583 of file collections.py.

00583 
00584     def __repr__(self):
00585         if not self:
00586             return '%s()' % self.__class__.__name__
00587         items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
00588         return '%s({%s})' % (self.__class__.__name__, items)

Here is the call graph for this function:

def collections.Counter.__sub__ (   self,
  other 
)
Subtract count, but keep only results with positive counts.

>>> Counter('abbbc') - Counter('bccd')
Counter({'b': 2, 'a': 1})

Definition at line 617 of file collections.py.

00617 
00618     def __sub__(self, other):
00619         ''' Subtract count, but keep only results with positive counts.
00620 
00621         >>> Counter('abbbc') - Counter('bccd')
00622         Counter({'b': 2, 'a': 1})
00623 
00624         '''
00625         if not isinstance(other, Counter):
00626             return NotImplemented
00627         result = Counter()
00628         for elem, count in self.items():
00629             newcount = count - other[elem]
00630             if newcount > 0:
00631                 result[elem] = newcount
00632         for elem, count in other.items():
00633             if elem not in self and count < 0:
00634                 result[elem] = 0 - count
00635         return result

Here is the call graph for this function:

Here is the caller graph for this function:

def collections.Counter.copy (   self)

Definition at line 571 of file collections.py.

00571 
00572     def copy(self):
00573         'Return a shallow copy.'
00574         return self.__class__(self)

Iterator over elements repeating each as many times as its count.

>>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C']

# Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
>>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
>>> product = 1
>>> for factor in prime_factors.elements():     # loop over factors
...     product *= factor                       # and multiply them
>>> product
1836

Note, if an element's count has been set to zero or is a negative
number, elements() will ignore it.

Definition at line 480 of file collections.py.

00480 
00481     def elements(self):
00482         '''Iterator over elements repeating each as many times as its count.
00483 
00484         >>> c = Counter('ABCABC')
00485         >>> sorted(c.elements())
00486         ['A', 'A', 'B', 'B', 'C', 'C']
00487 
00488         # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
00489         >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
00490         >>> product = 1
00491         >>> for factor in prime_factors.elements():     # loop over factors
00492         ...     product *= factor                       # and multiply them
00493         >>> product
00494         1836
00495 
00496         Note, if an element's count has been set to zero or is a negative
00497         number, elements() will ignore it.
00498 
00499         '''
00500         # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
00501         return _chain.from_iterable(_starmap(_repeat, self.items()))

Here is the call graph for this function:

def collections.Counter.fromkeys (   cls,
  iterable,
  v = None 
)

Definition at line 505 of file collections.py.

00505 
00506     def fromkeys(cls, iterable, v=None):
00507         # There is no equivalent method for counters because setting v=1
00508         # means that no element can have a count greater than one.
00509         raise NotImplementedError(
00510             'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')

def collections.Counter.most_common (   self,
  n = None 
)
List the n most common elements and their counts from the most
common to the least.  If n is None, then list all element counts.

>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]

Definition at line 467 of file collections.py.

00467 
00468     def most_common(self, n=None):
00469         '''List the n most common elements and their counts from the most
00470         common to the least.  If n is None, then list all element counts.
00471 
00472         >>> Counter('abcdeabcdabcaba').most_common(3)
00473         [('a', 5), ('b', 4), ('c', 3)]
00474 
00475         '''
00476         # Emulate Bag.sortedByCount from Smalltalk
00477         if n is None:
00478             return sorted(self.items(), key=_itemgetter(1), reverse=True)
00479         return _heapq.nlargest(n, self.items(), key=_itemgetter(1))

Here is the call graph for this function:

Here is the caller graph for this function:

def collections.Counter.subtract (   self,
  iterable = None,
  kwds 
)
Like dict.update() but subtracts counts instead of replacing them.
Counts can be reduced below zero.  Both the inputs and outputs are
allowed to contain zero and negative counts.

Source can be an iterable, a dictionary, or another Counter instance.

>>> c = Counter('which')
>>> c.subtract('witch')             # subtract elements from another iterable
>>> c.subtract(Counter('watch'))    # subtract elements from another counter
>>> c['h']                          # 2 in which, minus 1 in witch, minus 1 in watch
0
>>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch
-1

Definition at line 544 of file collections.py.

00544 
00545     def subtract(self, iterable=None, **kwds):
00546         '''Like dict.update() but subtracts counts instead of replacing them.
00547         Counts can be reduced below zero.  Both the inputs and outputs are
00548         allowed to contain zero and negative counts.
00549 
00550         Source can be an iterable, a dictionary, or another Counter instance.
00551 
00552         >>> c = Counter('which')
00553         >>> c.subtract('witch')             # subtract elements from another iterable
00554         >>> c.subtract(Counter('watch'))    # subtract elements from another counter
00555         >>> c['h']                          # 2 in which, minus 1 in witch, minus 1 in watch
00556         0
00557         >>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch
00558         -1
00559 
00560         '''
00561         if iterable is not None:
00562             self_get = self.get
00563             if isinstance(iterable, Mapping):
00564                 for elem, count in iterable.items():
00565                     self[elem] = self_get(elem, 0) - count
00566             else:
00567                 for elem in iterable:
00568                     self[elem] = self_get(elem, 0) - 1
00569         if kwds:
00570             self.subtract(kwds)

Here is the caller graph for this function:

def collections.Counter.update (   self,
  iterable = None,
  kwds 
)
Like dict.update() but add counts instead of replacing them.

Source can be an iterable, a dictionary, or another Counter instance.

>>> c = Counter('which')
>>> c.update('witch')           # add elements from another iterable
>>> d = Counter('watch')
>>> c.update(d)                 # add elements from another counter
>>> c['h']                      # four 'h' in which, witch, and watch
4

Definition at line 511 of file collections.py.

00511 
00512     def update(self, iterable=None, **kwds):
00513         '''Like dict.update() but add counts instead of replacing them.
00514 
00515         Source can be an iterable, a dictionary, or another Counter instance.
00516 
00517         >>> c = Counter('which')
00518         >>> c.update('witch')           # add elements from another iterable
00519         >>> d = Counter('watch')
00520         >>> c.update(d)                 # add elements from another counter
00521         >>> c['h']                      # four 'h' in which, witch, and watch
00522         4
00523 
00524         '''
00525         # The regular dict.update() operation makes no sense here because the
00526         # replace behavior results in the some of original untouched counts
00527         # being mixed-in with all of the other counts for a mismash that
00528         # doesn't have a straight-forward interpretation in most counting
00529         # contexts.  Instead, we implement straight-addition.  Both the inputs
00530         # and outputs are allowed to contain zero and negative counts.
00531 
00532         if iterable is not None:
00533             if isinstance(iterable, Mapping):
00534                 if self:
00535                     self_get = self.get
00536                     for elem, count in iterable.items():
00537                         self[elem] = count + self_get(elem, 0)
00538                 else:
00539                     super().update(iterable) # fast path when counter is empty
00540             else:
00541                 _count_elements(self, iterable)
00542         if kwds:
00543             self.update(kwds)

Here is the caller graph for this function:


The documentation for this class was generated from the following file: