我认为这是安全的:
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中是懒惰的。它不会尝试获取值(并引发异常,因为dict中没有这样的键)因为第一个条件已经不满足。但我可以依靠懒惰并在我的程序中使用第二个例子吗?
答案 0 :(得分:13)
是的,它是安全的,如果第一个表达式结果为False,Python就会短路,也就是说它不会评估if
条件下的第二个表达式。
但更好的方法是使用.get()
,如果字典中没有键,则返回None
。示例 -
if test_dict.get(key) == 'spam':
print('Spam detected!')
答案 1 :(得分:3)
and test_dict[key] == 'spam':
为if key in test_dict
时才会评估 True
,它的行为与您嵌套if的第一个代码完全相同。
当您使用and
时,表达式的两边必须为True,因此如果key in test_dict
返回False,则代码将短路。
使用and
方法实际上效率最高,尤其是当表达式的左侧为False时:
In [13]: d = {k:k for k in range(10000)}
In [14]: timeit 99999 in d and d[100] == "foo"
10000000 loops, best of 3: 48.2 ns per loop
In [15]: timeit d.get(9000) == "foo"
10000000 loops, best of 3: 155 ns per loop
In [16]: timeit 100 in d and d[100] == "foo
10000000 loops, best of 3: 119 ns per loo
In [17]: timeit d.get(100) == "foo"
10000000 loops, best of 3: 141 ns per loop