.counter python

28

from collections import Counter
strl = "aabbaba"
print(Counter(str1))

Counter({'a': 4, 'b': 3})
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)
Counter({'x': 4, 'y': 2, 'z': 2})

Comments

Submit
0 Comments