python中Counter是什么意思?

2025-12-01 0 12,844

 

大家对Counter的认知大多都局限于计数上面,其本身是字典中的子类,可以用于计数可哈希的对象,并且元素可以像key一样进行存储,能够利用Counter实现对可迭代对象计数、根据键引用值、删除一个键值对等等,在作为计数器上,counter是绝对简单高效的,下面就一起来了解具体使用技巧吧。

Counter对象可以使用字典的所有方法:

1、创建Counter对象

from collections import Counter
c = Counter()      
c = Counter('gallahad')    
c = Counter({'red': 4, 'blue': 2})   
c = Counter(cats=4, dogs=8)

 2、对可迭代对象进行计数

from collections import Counter
c = Counter('bananas')
c

3、根据键引用值

from collections import Counter
c = Counter('bananas')
c['a']

4、如果不存在该键,则返回0

from collections import Counter
c = Counter('bananas')
c['u']

5、删除其中一个键值对

from collections import Counter
c = Counter('bananas')
del c['a']
C

6、用映射来创建一Counter,并返回迭代器

from collections import Counter
c = Counter({'red': 3, 'blue': 1,'black':2})   
list(c.elements())

7、查看出现频次最高的前n元素及其次数

from collections import Counter
c = Counter('absabasdvdsavssaffsdaws')
c.most_common(3)

8、转换成字典

from collections import Counter
c = Counter('bananas')
dict(c)

从上述内容,我们基本上可以获悉Counter对象可以进行加减运算及逻辑运算操作,在学习语言上,最好的学习就是掌握使用技巧,大家多多了解掌握住吧~

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python基础 python中Counter是什么意思? https://www.zhiup.top/3586.html

相关