from collections import Counter计数器

本文深入讲解了Python中collections模块下的Counter类,包括如何对字符串、列表、元组和字典进行计数,以及如何使用most_common、elements、update、subtract等方法。通过实例演示了Counter在数据统计和操作上的强大功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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})

6. iteritems() (同字典的items(),返回迭代器)

7. iterkeys() (同字典的keys(),返回迭代器)

8. itervalues() (同字典的values(),返回迭代器)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值