import collections
arr = ['a', 'a', 'b', 'b', 'b', 'c']
# set the elements frequencies using Counter class
elements_count = collections.Counter(arr)
# printing the element and the frequency
for key, value in elements_count.items():
print(f"{key}: {value}")
# output
# a: 2
# b: 3
# c: 1
data = 'hello world'
# set the elements frequencies using Counter class
elements_count = collections.Counter(data)
# printing the element and the frequency
print(elements_count)
>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
... cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
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 += Counter() # remove zero and negative counts
c = Counter("thiiss wiill caalcullateeee theee numbeeer of characters")
# now when we print c, it will have the following data:
Counter({'e': 11, ' ': 6, 'l': 5, 'a': 5, 't': 4, 'i': 4, 'c': 4, 'h': 3, 's': 3, 'r': 3, 'u': 2, 'w': 1, 'n': 1, 'm': 1, 'b': 1, 'o': 1, 'f': 1})
# And now we can check the occurrence of each of the characters as follows:
count_e = c.get('e') # returns 11
import time
from time import sleep, time
can_run = True
the_number = 0
end_number = 11 #you can change the number to be last counted
while can_run:
print(the_number)
sleep(1)
the_number = the_number + 1
if the_number == end_number:
can_run = False