Python Forum
collections.Counter()
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
collections.Counter()
#1
The Counter() in the collections module is a dictionary-like object that keeps distinct elements as keys with their counts as the values. We can use the class to get the occurrences of each element in a given iterable.

#import the Counter class from collections module
from collections import Counter

#An iterable with elements to count
data = 'aabbbccccdeefff'

#create the Counter object
c = Counter(data)

print(c)

#get the count of a specific element
print(c['f'])
Output:
Counter({'c': 4, 'b': 3, 'f': 3, 'a': 2, 'e': 2, 'd': 1}) 3
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020