
此映射类型为键准备了一个整数计数器。每更新一次键,该计数器就增加一次。因此,此类型可用于为可散列表对象计数,或将其作为多重集合使用——多重集合就是集合中的元素可以多次出现。
1、Counter 实现了 + 和 - 运算符用来合并记录,还有像 most_common([n]) 这类很有用的方法。most_common([n]) 会按照次序返回映射里最常见的 n 个键和它们的计数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | In [1]: from collections import Counter
In [2]: langs = [ 'java' , 'php' , 'python' , 'C#' , 'kotlin' , 'swift' , 'python' ]
In [3]: ct = Counter(langs)
In [4]: ct
Out[4]: Counter({ 'C#' : 1, 'java' : 1, 'kotlin' : 1, 'php' : 1, 'python' : 2, 'swift' : 1})
In [5]: ct.update([ 'java' , 'c' ])
In [6]: ct
Out[6]:
Counter({ 'C#' : 1,
'c' : 1,
'java' : 2,
'kotlin' : 1,
'php' : 1,
'python' : 2,
'swift' : 1})
In [7]: ct.most_common(2)
Out[7]: [( 'java' , 2), ( 'python' , 2)]
|
2、直接操作字符串
1 2 3 4 5 6 7 8 9 10 11 12 | In [9]: ct = Counter( 'abracadabra' )
In [10]: ct
Out[10]: Counter({ 'a' : 5, 'b' : 2, 'c' : 1, 'd' : 1, 'r' : 2})
In [11]: ct.update( 'aaaaazzz' )
In [12]: ct
Out[12]: Counter({ 'a' : 10, 'b' : 2, 'c' : 1, 'd' : 1, 'r' : 2, 'z' : 3})
In [13]: ct.most_common(2)
Out[13]: [( 'a' , 10), ( 'z' , 3)]
|
以上就是Counter在python中两种用法,希望能对大家有所帮助,更多知识尽在python学习网。