有时候只是想统计一串日志级别、标签或者状态码出现了几次,手写 dict 加一堆 if key not in 会有点啰嗦。标准库的 Counter 挺适合这种小活。
环境:Python 3.8+。保存成 counter-demo.py:
from collections import Counter
levels = ['info', 'warn', 'info', 'error', 'warn', 'info']
counts = Counter(levels)
print(counts)
print(counts['info'])
print(counts.most_common(2))
print(counts['debug'])
跑一下:
python counter-demo.py
most_common(2) 会拿到出现最多的两个项。没出现过的 key 读出来是 0,这一点写临时统计脚本时还挺舒服。
不过它也只是计数工具,如果后面要按时间窗口、用户维度之类的复杂聚合,还是早点换成更清楚的数据结构比较好。