举例:
from collections import Counter
s = "hello-python-hello-world"
a = Counter(s)
print(a)
# 结果
Counter({'-': 3, 'd': 1, 'e': 2, 'h': 3, 'l': 5, 'n': 1, 'o': 4, 'p': 1, 'r': 1, 't': 1, 'w': 1, 'y': 1})
举例:
print(a.most_common(3))
# 结果
[('l', 5), ('o', 4), ('h', 3)] 出现次数最多的三个元素
举例:
for i in a.elements():
print(i, end="")
# 结果:
hhheellllloooo---pytnwrd
举例:
a.update("hello123121")
print(a)
# 结果:
Counter({'-': 3, '1': 3, '2': 2, '3': 1, 'd': 1, 'e': 3, 'h': 4, 'l': 7, 'n': 1, 'o': 5, 'p': 1, 'r': 1, 't': 1, 'w': 1, 'y': 1})
s1 = "abcd"
s2 = "cdef"
a1 = Counter(s1)
a2 = Counter(s2)
a1.subtract(a2)
print(a1)
# 结果:
Counter({'a': 1, 'b': 1, 'c': 0, 'd': 0, 'e': -1, 'f': -1})