
Python Counter - Count the elements of a list or tuple
You can count the elements in a list or tuple using the Counter
class from Python 3.1.
from collections import Counter
a = ['in', 'in', 'of', 'of', 'of', 'with']
c = Counter(a)
print(c) # Counter({'of': 3, 'in': 2, 'with': 1})
print(type(c)) # <class 'collections.Counter'>
The Counter class is a dict subclass and the number of elements are its values.
Create the Counter object from a tuple
from collections import Counter
t = ('a', 'a', 'b')
c = Counter(t)
print(c)
# Counter({'a': 2, 'b': 1})
Count Elements
from collections import Counter
s = ['in', 'in', 'of', 'of', 'of', 'with']
c = Counter(s)
of = c['of']
print(of) # 3
In case the counter doesn't contain a given element, the count is zero.
from collections import Counter
s = ['in', 'in', 'of', 'of', 'of', 'with']
c = Counter(s)
the = c['the']
print(the) # 0
Append and update the Counter object
from collections import Counter
c = Counter(x=3, y=2)
print(c)
# Counter({'x': 3, 'y': 2})
c['z'] = 1
print(c)
# Counter({'x': 3, 'y': 2, 'z': 1})
The above is an example of appending and the following is one of updating.
from collections import Counter
c = Counter(x=3, y=2)
print(c)
# Counter({'x': 3, 'y': 2})
c['x'] = 1
print(c)
# Counter({'y': 2, 'x': 1})
Get most common elements and counts
from collections import Counter
s = ['a', 'a', 'a', 'b', 'b', 'c']
c = Counter(s)
m = c.most_common()
print(m) # [('a', 3), ('b', 2), ('c', 1)]
m1 = c.most_common(1)
m2 = c.most_common(2)
m3 = c.most_common(3)
m4 = c.most_common(4)
print(m1) # [('a', 3)]
print(m2) # [('a', 3), ('b', 2)]
print(m3) # [('a', 3), ('b', 2), ('c', 1)]
print(m4) # [('a', 3), ('b', 2), ('c', 1)]
The most_common(n) method returns the n
pairs of most common elements and their counts. In case of omitting the argument, it returns all the elements and counts.
Get all the elements
from collections import Counter
c = Counter(a=2, b=1)
elements = c.elements()
print(elements) # <itertools.chain object at 0x10a32b310>
print(type(elements)) # <class 'itertools.chain'>
s = list(elements)
print(s) # ['a', 'a', 'b']
Appending the original list
from collections import Counter
s = ['a', 'a', 'b']
c = Counter(s)
print(c) # Counter({'a': 2, 'b': 1})
print(c['a']) # 2
s.append('a')
print(c) # Counter({'a': 2, 'b': 1})
print(c['a']) # 2
Appending the list doesn't update the counter.
Comments
Powered by Markdown