How to do it...

  1. Here is how to create a new Counter object, as demonstrated from https://docs.python.org/3/library/collections.html#collections.Counter:
      >>> from collections import Counter
>>> c = Counter() # a new, empty counter

>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8) # a new counter from keyword args
    • The first object is simply an empty counter, much like creating an empty dictionary.
      The second Counter creates a mapping of a text string, summing the count of each unique letter, is as follows:
                   >>> c
Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1})
    • The third Counter object is a direct creation from a dictionary, with the quantity of each key provided by the user.
    • The final object is similar to the previous, except keyword arguments rather than a dictionary mapping.
  1. Interaction with a Counter is the same as with dictionaries, except they have been optimized to return a value of 0 if an item doesn't exist within the Counter, rather than raising an error:
      >>> count = Counter(["spam", "eggs", "bacon"])
>>> count["toast"]
0
>>> count
Counter({'spam': 1, 'eggs': 1, 'bacon': 1})
  1. The del statement must be used to remove an element from a Counter. Simply changing its value to zero only changes the value while leaving the element within the Counter:
      >>> count["bacon"] = 0 # assigning a value of 0 to "bacon"
>>> count
Counter({'spam': 1, 'eggs': 1, 'bacon': 0})
>>> del count["bacon"] # del must be used to actually remove "bacon"
>>> count
Counter({'spam': 1, 'eggs': 1})
  1. This is how to iterate over the Counter elements:
      >>> count.elements()  # iterators create an object in memory
<itertools.chain object at 0x7f210f769a90>
>>> sorted(count.elements())
# use another function to actually print the iterated values

['eggs', 'spam']
  1. This is how to retrieve the most common elements in a Counter object:
      >>> c = Counter('gallahad')
>>> c.most_common() # return all values
[('a', 3), ('l', 2), ('g', 1), ('h', 1), ('d', 1)]
>>> c.most_common(3) # return top three
[('a', 3), ('l', 2), ('g', 1)]
  1. This is how to subtract values from elements:
      >>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
>>> c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
  1. As noted in the Python documentation (https://docs.python.org/3/library/collections.html#collections.Counter), there are a number of common operations when working with Counters, that are listed below. Some may be obvious, as Counters are a type of dictionary; others are unique to Counters due to their number-centric behavior:
        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 # remove zero and negative counts
  1. Because Counters are unique dictionaries, there are some math operations available to Counters to allow the combining of Counter objects into multisets (Counters that have counts greater than zero). Some of these are basic arithmetic, while others are similar to what sets has available.

Addition and subtraction add/subtract the elements of different Counter objects. Intersection and union return the minimum and maximum elements from their Counter objects. While signed integers are used as input, any values that would have an output value of zero or less are ignored and not returned. If negative values or zero are used as inputs, only outputs with positive values are returned:

      >>> c = Counter(a=3, b=1)
      >>> d = Counter(a=1, b=2)
      >>> c + d           #  add two counters  together:  c[x] + d[x]
      Counter({'a': 4, 'b': 3})
      >>> c - d           #  subtract (keeping only positive counts)
      Counter({'a': 2})
      >>> c & d           #  intersection:  min(c[x], d[x]) 
      Counter({'a': 1, 'b': 1})
      >>> c | d           #  union:  max(c[x], d[x])
      Counter({'a': 3, 'b': 2})
  1. As noted in step 7 earlier, unary shortcuts are available for adding an empty Counter or subtracting from an empty Counter:
      >>> c = Counter(a=2, b=-4)
>>> +c # removes negative and zero values
Counter({'a': 2})
>>> -c # inverts signs; negative values are ignored
Counter({'b': 4})
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset