品易云推流 关闭
文章详情页
文章 > 头条 > python中Counter是什么意思?

python中Counter是什么意思?

头像

十一

2021-01-25 10:38:3214658浏览 · 0收藏 · 0评论

 

大家对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对象可以进行加减运算及逻辑运算操作,在学习语言上,最好的学习就是掌握使用技巧,大家多多了解掌握住吧~

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图