为什么KeyError会以逻辑AND而不是逻辑OR抛出 [英] Why does a KeyError get thrown in logical AND but not in a logical OR
问题描述
我有一个特定的字符串k
,它可能是或可能不是dict reversedmapping
的键,还有另一个dict spendDict
,它也可能是键.
I have a certain string k
that may or many not a key of a dict reversedmapping
, and another dict spendDict
where it may also be a key.
对于不是k reversedmapping
键的k值,为什么以下检查成功(即运行到完成):
Why does the following check succeed (i.e. run to completion), for a value of k that is not a key of reversedmapping
:
if (k not in reversedmapping) or (reversedmapping[k] not in spendDict)
当我将其更改为逻辑AND时,我得到一个KeyError
(对于k):
whereas I get a KeyError
(for k) when I change it to logical AND:
if (k not in reversedmapping) and (reversedmapping[k] not in spendDict)
:
以及如何重写AND变体以避免KeyError?
And how do I rewrite the AND variant to avoid the KeyError?
推荐答案
如果(k not in reversedmapping)
是True
,则
(k not in reversedmapping) or (reversedmapping[k] not in spendDict)
短路 ,这意味着它会返回True
而不进行评估
(reversedmapping[k] not in spendDict)
由于True or anything
是True
.
相反,
(k not in reversedmapping) and (reversedmapping[k] not in spendDict)
必须先评估两个部分,然后Python才能确定总表达式
是True
.
must evaluate both parts before Python can determine that the total expression
is True
.
如果(k not in reversedmapping)
是True
,则reversedmapping[k]
将升高
KeyError
.
If (k not in reversedmapping)
is True
, then reversedmapping[k]
will raise
KeyError
.
如果(k not in reversedmapping)
是False
,则表达式短路
并返回False
,因为False and anything
是False
.
If (k not in reversedmapping)
is False
, then the expression short-circuits
and returns False
since False and anything
is False
.
所以
(k not in reversedmapping) and (reversedmapping[k] not in spendDict)
将始终返回False
或引发KeyError
.没有任何情况
在此情况下,它可以返回True
. 两个条件都不能为真.
will always either return False
or raise a KeyError
. There is no situation
under which it could return True
. Both conditions can not be True.
这篇关于为什么KeyError会以逻辑AND而不是逻辑OR抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!