Counter:字典的子类,提供了可哈希对象的计数功能。

它存储的键为元素,存储的值为元素的数量。

其中,”Elements are counted from an iterable or initialized from another mapping (or counter)”。

Counter的创建与删除

我们可以使用如下的几个方法创建Counter对象。

1
2
3
4
c = Counter() # 一个空的Counter
c = Counter("english") # 一个迭代对象生成的Counter
c = Counter(['red':4,'blue':2]) # 一个映射生成的Counter
c = Counter(cats=4,dogs=8) # 一个关键词参数生成的Counter

在Counter中,对于不存在的键,Counter不会返回异常而是直接返回0。

1
2
c = Counter(['eggs','apples'])
print(c['orange']) # output:0 不会返回异常

在Counter中,直接设置一个键的值为0,不会导致这个键被删除。如果需要删除Counter中的一个键,我们需要使用 del 来完成此操作。这是在3.1版本中被添加的新特性。

1
2
c['apples'] = 0 # apples这个键不会被删除
del c['apples'] = 0 # 完全删除apples这个键

Counter中的方法

Counter作为Dict的子类,除了继承了Dict的全部方法,还要如下的几个新方法:

  • elements() # 返回一个迭代器,存储了每个元素的个数。其中迭代器中元素的顺序为Counter遇见它们时的顺序。另外,如果元素的个数小于1,那么将不会返回这个元素,负数也算。
1
2
3
c = Counter(a=3,b=2,c=0,d=-1)
sorted(c.elements())
# output:['a', 'a', 'a', 'a', 'b', 'b']
  • most_common([ n ]) # 返回前n个出现次数最多的元素和它们出现的次数。如果n超过元素总数,或者n是 None ,那么就会返回所有的元素。
1
2
Counter('abracadabra').most_common(3)
# output:[('a', 5), ('b', 2), ('r', 2)]
  • subtract([ iterable-or-mapping ]) # 依据输入的 iterable 或者 mapping ,减去元素的数量。输入和输出都可以是0或者是负数。
1
2
3
4
c = Counter(a=3,b=2,c=1)
d = Counter(a=-1,b=2,c=0)
c.subtract(d)
# output:Counter({'a': 4, 'c': 1, 'b': 0}) # 当前c的值

以下的两个方法在Counter中的用法与Dict中的用法有着少许不同。

  • fromkeys( iterable ) # 这个方法在Counter中并没有被实现。
  • update([ iterable-or-mapping ]) # 跟subtract()函数的用法一致,不过这里是加法不是减法。另外,这里的 iterable 希望是元素序列,而不是键值对序列。

其他

除了使用函数来实现Counter的加减操作,我们也可以使用运算符来实现。对于Counter对象,我们可以使用 + 符号实现加法运算,使用 - 符号实现减法运算,使用 & 符号实现交操作和使用 | 实现并操作。

1
2
3
4
5
6
7
8
9
10
c = Counter(a=3, b=1)
d = Counter(a=1, b=2)
c + d # add two counters together: c[x] + d[x]
# Counter({'a': 4, 'b': 3})
c - d # subtract (keeping only positive counts)
# Counter({'a': 2})
c & d # intersection: min(c[x], d[x])
Counter({'a': 1, 'b': 1})
c | d # union: max(c[x], d[x])
# Counter({'a': 3, 'b': 2})

此外,进制加法和减法是添加空计数器或从空计数器中减去的快捷方式。原文如下:”Unary addition and subtraction are shortcuts for adding an empty counter or subtracting from an empty counter.”

1
2
3
4
5
c = Counter(a=2, b=-4)
+c
# Counter({'a': 2})
-c
# Counter({'b': 4})

一些常见的Counter对象使用方式:

1
2
3
4
5
6
7
8
9
sum(c.values())                 # 继承自字典的.values()方法返回values的列表,再求和
c.clear() # 继承自字典的.clear()方法,清空counter
list(c) # 返回key组成的list
set(c) # 返回key组成的set
dict(c) # 转化成字典
c.items() # 转化成(元素,计数值)组成的列表
Counter(dict(list_of_pairs)) # 从(元素,计数值)组成的列表转化成Counter
c.most_common()[:-n-1:-1] # 最小n个计数的(元素,计数值)组成的列表
+c # 去除负值和0的值

参考