大家对Counter的认知大多都局限于计数上面,其本身是字典中的子类,可以用于计数可哈希的对象,并且元素可以像key一样进行存储,能够利用Counter实现对可迭代对象计数、根据键引用值、删除一个键值对等等,在作为计数器上,counter是绝对简单高效的,下面就一起来了解具体使用技巧吧。
Counter对象可以使用字典的所有方法:
1、创建Counter对象
1 2 3 4 5 | from collections import Counter
c = Counter()
c = Counter( 'gallahad' )
c = Counter({ 'red' : 4, 'blue' : 2})
c = Counter(cats=4, dogs=8)
|
2、对可迭代对象进行计数
1 2 3 | from collections import Counter
c = Counter( 'bananas' )
c
|
3、根据键引用值
1 2 3 | from collections import Counter
c = Counter( 'bananas' )
c[ 'a' ]
|
4、如果不存在该键,则返回0
1 2 3 | from collections import Counter
c = Counter( 'bananas' )
c[ 'u' ]
|
5、删除其中一个键值对
1 2 3 4 | from collections import Counter
c = Counter( 'bananas' )
del c[ 'a' ]
C
|
6、用映射来创建一个Counter,并返回迭代器
1 | <strong>from collections import Counter<br>c = Counter({ 'red' : 3, 'blue' : 1, 'black' :2}) <br>list(c.elements())<br></strong>
|
7、查看出现频次最高的前n元素及其次数
1 2 3 | from collections import Counter
c = Counter( 'absabasdvdsavssaffsdaws' )
c.most_common(3)
|
8、转换成字典
1 2 3 | from collections import Counter
c = Counter( 'bananas' )
dict(c)
|
从上述内容,我们基本上可以获悉Counter对象可以进行加减运算及逻辑运算操作,在学习语言上,最好的学习就是掌握使用技巧,大家多多了解掌握住吧~