1. 对字符串\列表\元祖\字典进行计数,返回一个字典类型的数据,键是元素,值是元素出现的次数
举例:
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})
2. most_common(n) (统计出现最多次数的n个元素)
举例:
print(a.most_common(3))
# 结果
[('l', 5), ('o', 4), ('h', 3)] 出现次数最多的三个元素
3. elements (返回一个Counter计数后的各个元素的迭代器)
举例:
for i in a.elements():
print(i, end="")
# 结果:
hhheellllloooo---pytnwrd
4. update (类似集合的update,进行更新)
举例:
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})
5. subtract (类似update,做减法)
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})