In [16]:
import collections
In [10]:
# called with a sequence of item
init_list = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
init_str = collections.Counter({'a': 2, 'b': 3, 'c': 1})
In [11]:
print(init_list)
print('*'*40)
print(init_str)
In [12]:
# a dictionary containing keys and counts
init_dict = collections.Counter({'a': 2, 'b': 3, 'c': 1})
print(init_dict)
In [13]:
# keyword arguments that map string to counts
init_keyword=collections.Counter(a=2,b=3,c=1)
print(init_keyword)
In [20]:
# keyword arguments that map string to counts
# the count can be any integer value, including, \
# zero and negative counts
init_nonpositive=collections.Counter(a=2,b=3,c=1,d=-1,e=0)
print(init_nonpositive)
In [14]:
# of course, we can build empty Counter
init_empty = collections.Counter()
print(init_empty)
In [17]:
import collections
c = collections.Counter('abcdaab')
for letter in 'abcde':
print('{} : {}'.format(letter, c[letter]))
Note:
Counter don't raise KeyError
for unknown items, If a value has not seen in the input, its count is 0
In [21]:
import collections
c = collections.Counter('extremely')
c['z'] = 0
print(c)
print(list(c.elements()))
In [22]:
import collections
c = collections.Counter()
with open('/usr/share/dict/words', 'rt') as f:
for line in f:
c.update(line.rstrip().lower())
print('Most common:')
for letter, count in c.most_common(3):
print('{}: {:>7}'.format(letter, count))
In [25]:
# update with iterabal
import collections
c = collections.Counter('extremely')
print("before update: ", c)
print("*"*40)
c.update("aell")
print("after update:", c)
In [26]:
# update with mapping
c = collections.Counter('extremely')
print("before update: ", c)
print("*"*40)
c.update({'e':10,'t':1})
print("after update:", c)
In [27]:
import collections
c = collections.Counter('extremely')
print("before update: ", c)
print("*"*40)
c.subtract("aell")
print("after update:", c)
In [28]:
import collections
c1 = collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
c2 = collections.Counter('alphabet')
print('C1:', c1)
print('C2:', c2)
print('\nCombined counts:')
print(c1 + c2)
print('\nSubtraction:')
print(c1 - c2)
print('\nIntersection (taking positive minimums):')
print(c1 & c2)
print('\nUnion (taking maximums):')
print(c1 | c2)
In [ ]: