2.2.2.3 算术操作
Counter实例支持用算术和集合操作来完成结果的聚集。下面这个例子展示了创建新Counter实例的标准操作符,不过也支持+=,-=,&=和|=等原地执行的操作符。
import collections
c1 = collections.Counter(['a','b','c','a','b','b'])
c2 = collections.Counter('alphabet')
print('C1:',c1)
print('C2:',c2)
print('\nCombined counts:')
print(c1 + c2)
print('\nSubtraction:')
print(c1 - c2)
print('\nIntersection(taking positive minimums):')
print(c1 & c2)
print('\nUnion(taking maximums):')
print(c1 | c2)
每次通过一个操作生成的新的Counter时,计数为0或负数的元素都会被删除。在c1和c2中a的计数相同,所以减法操作后它的计数为0。
运行结果:
C1: Counter({‘b’: 3, ‘a’: 2, ‘c’: 1})
C2: Counter({‘a’: 2, ‘l’: 1, ‘p’: 1, ‘h’: 1, ‘b’: 1, ‘e’: 1, ‘t’: 1})
Combined counts:
Counter({‘a’: 4, ‘b’: 4, ‘c’: 1, ‘l’: 1, ‘p’: 1, ‘h’: 1, ‘e’: 1, ‘t’: 1})
Subtraction:
Counter({‘b’: 2, ‘c’: 1})
Intersection(taking positive minimums):
Counter({‘a’: 2, ‘b’: 1})
Union(taking maximums):
Counter({‘b’: 3, ‘a’: 2, ‘c’: 1, ‘l’: 1, ‘p’: 1, ‘h’: 1, ‘e’: 1, ‘t’: 1})