Python 一行代码实现计数统计:dict.get()的巧妙用法
在 Python 中统计元素出现次数是一个常见需求。今天分享一个经典且优雅的写法,只需一行代码就能搞定:
app_stats[entry.app_id]=app_stats.get(entry.app_id,0)+1场景还原
假设我们在分析日志,需要统计每个app_id出现的次数:
fromtypingimportDict# 假设 self.entries 包含多条日志记录app_stats:Dict[int,int]={}# 用于存储统计结果forentryinself.entries:# 统计每个 app_id 出现的次数app_stats[entry.app_id]=app_stats.get(entry.app_id,0)+1# 输出结果示例:{15: 3, 16: 2, 17: 1}# 表示 app_id=15 出现3次,16出现2次,17出现1次拆解这行代码
app_stats[entry.app_id]=app_stats.get(entry.app_id,0)+1│ │ │ │ │ │ │ │ │ └─ 如果不存在,从0开始计数 │ │ │ └─ 查找的键(app_id) │ │ └─ dict.get(key,default)方法 │ └─ 将结果存回字典 └─ 目标字典执行逻辑:
| 情况 | get()返回值 | 计算结果 | 效果 |
|---|---|---|---|
app_id第一次出现 | 0(默认值) | 0 + 1 = 1 | 初始化计数为1 |
app_id已存在 | 当前计数(如3) | 3 + 1 = 4 | 计数加1 |
为什么用get()而不是[]?
Python 字典有两种访问方式:
# 方式1:用 [] 访问(不推荐用于计数)app_stats[15]# 如果15不存在,直接抛出 KeyError!# 方式2:用 get() 访问(推荐)app_stats.get(15,0)# 如果15不存在,返回默认值 0,不报错dict.get(key, default)的优势:
- 键存在时:返回对应的值
- 键不存在时:返回指定的默认值(不会报错)
- 完美适合"第一次初始化,之后累加"的场景
执行流程图解
假设日志中的app_id序列为:[15, 15, 15, 16, 16]
初始:app_stats={}第1次(15):get(15,0)→ 返回0→0+1=1→ app_stats={15:1}第2次(15):get(15,0)→ 返回1→1+1=2→ app_stats={15:2}第3次(15):get(15,0)→ 返回2→2+1=3→ app_stats={15:3}第4次(16):get(16,0)→ 返回0→0+1=1→ app_stats={15:3,16:1}第5次(16):get(16,0)→ 返回1→1+1=2→ app_stats={15:3,16:2}最终结果:{15:3,16:2}对比:冗长写法 vs 简洁写法
传统写法(需要 if-else):
ifentry.app_idinapp_stats:app_stats[entry.app_id]=app_stats[entry.app_id]+1else:app_stats[entry.app_id]=1优雅写法(一行搞定):
app_stats[entry.app_id]=app_stats.get(entry.app_id,0)+1对比结果:
- ✅ 代码更简洁(1行 vs 4行)
- ✅ 逻辑更清晰(无需分支判断)
- ✅ 效率更高(只查询一次字典)
实际应用场景
这种写法广泛应用于:
# 1. 词频统计word_count={}forwordintext.split():word_count[word]=word_count.get(word,0)+1# 2. 投票统计votes={}forvoteinballot:votes[vote]=votes.get(vote,0)+1# 3. 错误日志统计error_stats={}forerrorinlog_errors:error_stats[error.code]=error_stats.get(error.code,0)+1进阶:用 collections.Counter
如果你不需要手动控制过程,Python 提供了更高级的工具:
fromcollectionsimportCounter# 一行代码完成全部统计app_stats=Counter(entry.app_idforentryinself.entries)# 结果:Counter({15: 3, 16: 2})但在需要自定义统计逻辑或边遍历边处理的场景下,dict.get()的写法依然是最灵活、最经典的选择。
总结
stats[key]=stats.get(key,0)+1这行代码堪称 Python 计数字典的标准范式:
- 利用
get()的默认值特性,巧妙地解决了"初始化+累加"的问题 - 将原本需要条件判断的逻辑压缩成一行
- 既安全又高效,是 Pythonic 代码的典型代表
下次需要统计元素频次时,试试这行代码吧!