【发布时间】:2015-09-20 12:03:29
【问题描述】:
我认为这是安全的:
if key in test_dict:
if test_dict[key] == 'spam':
print('Spam detected!')
但是这样安全吗?
if key in test_dict and test_dict[key] == 'spam':
print('Spam detected!')
它应该做同样的事情,因为条件检查在 python 中是惰性的。它不会尝试获取值(并引发异常,因为字典中没有这样的键),因为第一个条件已经不满足。但是我可以依靠懒惰并在我的程序中使用第二个示例吗?
【问题讨论】:
-
是的,两个 sn-ps 都是等效的并且“安全”。
标签: python python-3.x dictionary