xxxxxxxxxx
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)
xxxxxxxxxx
from collections import Counter
strl = "aabbaba"
print(Counter(str1))
Counter({'a': 4, 'b': 3})
xxxxxxxxxx
# PYTHON 3
from collections import Counter
def example(data: str) -> Counter:
counted_letters = Counter(data) # Counts every character in the string
return counted_letters # {character: amount}
example('Data1233') # Counter({'D': 1, 'a': 2, 't': 1, '1': 1, '2': 1, '3': 2})
example('hello world') # Counter({'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
xxxxxxxxxx
import collections
c = collections.Counter()
print 'Initial :', c
c.update('abcdaab')
print 'Sequence:', c
c.update({'a':1, 'd':5})
print 'Dict :', c
xxxxxxxxxx
import collections
print collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
print collections.Counter({'a':2, 'b':3, 'c':1})
print collections.Counter(a=2, b=3, c=1)
xxxxxxxxxx
>>> from collections import Counter
>>> colors = ['blue', 'blue', 'blue', 'red', 'red']
>>> counter = Counter(colors)
>>> counter['yellow'] += 1
Counter({'blue': 3, 'red': 2, 'yellow': 1})
>>> counter.most_common()[0]
('blue', 3)
xxxxxxxxxx
import collections
number = [0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1]
collections.Counter(number)
#output
#Counter({0: 12, 1: 9})
xxxxxxxxxx
>>> # 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)]
xxxxxxxxxx
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
xxxxxxxxxx
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