Counter() most_common()统计

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})
  1. iteritems() (同字典的items(),返回迭代器)
  2. iterkeys() (同字典的keys(),返回迭代器)
  3. itervalues() (同字典的values(),返回迭代器)

————————————————
版权声明:本文为CSDN博主「ch_improve」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/ch_improve/article/details/89388389

猜你喜欢

转载自blog.csdn.net/weixin_42462804/article/details/106122489
今日推荐