python字典get函数有一个很微妙的陷阱,代码如下:
>>> t={1:2}
>>> s={3:4}
>>> t.get(1,s[1])
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 1
>>> t.get(1,s.get(1,0))
2
python字典的get函数在执行时,会同时检查执行get函数的字典,同时还会去获取默认值,最后再决定返回值。
>>> t={1:2}
>>> s={3:4}
>>> t.get(1,s[1])
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 1
>>> t.get(1,s.get(1,0))
2
python字典的get函数在执行时,会同时检查执行get函数的字典,同时还会去获取默认值,最后再决定返回值。
本文揭示了Python字典get函数隐藏的陷阱,通过实例展示了正确使用get函数的方法,避免常见错误。
699

被折叠的 条评论
为什么被折叠?



