Counter Arithmetic Adds Subtracts Tallies

Combine tallies with Counter algebra: plus merges totals, minus cancels and drops non-positive counts, and intersection and union take mins and maxes.

PythonData Integrity

Code

pythonsnippet
21 lines
from collections import Counter

# Counter 支持代数运算:相加合并、相减抵消、交集取小、并集取大
monday = Counter({"orders": 12, "errors": 3, "deploys": 2})
tuesday = Counter({"orders": 9, "errors": 3, "deploys": 1})

print("total  :", monday + tuesday)
print("delta  :", monday - tuesday)
print("common :", monday & tuesday)
print("peak   :", monday | tuesday)

# 减到 0 以下的项会被丢弃:差集天然非负
delta = tuesday - monday
print("non-negative delta:", delta)

# 单项增减用 update / subtract,仍是同一只计数器
tally = Counter("mississippi")
tally.subtract({"s": 1})
tally.update(["m"])
print("letters:", dict(tally))
print("most common:", tally.most_common(2))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

total  : Counter({'orders': 21, 'errors': 6, 'deploys': 3})
delta  : Counter({'orders': 3, 'deploys': 1})
common : Counter({'orders': 9, 'errors': 3, 'deploys': 1})
peak   : Counter({'orders': 12, 'errors': 3, 'deploys': 2})
non-negative delta: Counter()
letters: {'m': 2, 'i': 4, 's': 3, 'p': 2}
most common: [('i', 4), ('s', 3)]

Inside the snippet

Module-level bindings hold the data — monday, tuesday, delta, tally — with no function scope in between.

Putting the pieces to work

The demo output is labeled (total :, delta :, common :), so every printed line maps back to its originating operation.

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. Every import resolves inside the standard library — `collections`. Its state lives in module-level bindings: `monday`, `tuesday`, `delta`.