Pau*_* S. 29 python dictionary increment
在Python中,在增加密钥之前必须首先检查密钥是否在字典中是很烦人的:
if key in my_dict:
my_dict[key] += num
else:
my_dict[key] = num
Run Code Online (Sandbox Code Playgroud)
以上四条线是否有较短的替代品?
Nic*_*tti 60
另一种选择是:
my_dict[key] = my_dict.get(key, 0) + num
Run Code Online (Sandbox Code Playgroud)
Ble*_*der 22
你有很多选择.我喜欢用Counter:
>>> from collections import Counter
>>> d = Counter()
>>> d[12] += 3
>>> d
Counter({12: 3})
Run Code Online (Sandbox Code Playgroud)
或者defaultdict:
>>> from collections import defaultdict
>>> d = defaultdict(int) # int() == 0, so the default value for each key is 0
>>> d[12] += 3
>>> d
defaultdict(<function <lambda> at 0x7ff2fe7d37d0>, {12: 3})
Run Code Online (Sandbox Code Playgroud)
转变:
if key in my_dict:
my_dict[key] += num
else:
my_dict[key] = num
Run Code Online (Sandbox Code Playgroud)
进入以下用途setdefault:
my_dict[key] = my_dict.setdefault(key, 0) + num
Run Code Online (Sandbox Code Playgroud)