Python字典增量 [英] Python dictionary increment

查看:146
本文介绍了Python字典增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,必须先检查字典中是否存在键,然后再递增它,这很烦人:

In Python it's annoying to have to check whether a key is in the dictionary first before incrementing it:

if key in my_dict:
  my_dict[key] += num
else:
  my_dict[key] = num

上面的四行有较短的替代品吗?

Is there a shorter substitute for the four lines above?

推荐答案

替代方法是:

my_dict[key] = my_dict.get(key, 0) + num

这篇关于Python字典增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆