本文翻译自:Why does “not(True) in [False, True]” return False?
If I do this: 如果我这样做:
>>> False in [False, True]
True
That returns True
. 返回True
。 Simply because False
is in the list. 只是因为False
在列表中。
But if I do: 但如果我这样做:
>>> not(True) in [False, True]
False
That returns False
. 返回False
。 Whereas not(True)
is equal to False
: 而not(True)
等于False
:
>>> not(True)
False
Why? 为什么?
#1楼
参考:https://stackoom.com/question/27q8R/为什么-False-True-中的-not-True-返回False
#2楼
Operator precedence. 运算符优先级。 in
binds more tightly than not
, so your expression is equivalent to not((True) in [False, True])
. in
绑定比not
紧,所以你的表达式相当于not((True) in [False, True])
。
#3楼
It's all about operator precedence ( in
is stronger than not
). 这是所有关于运算符优先级 ( in
要强于not
)。 But it can be easily corrected by adding parentheses at the right place: 但是可以通过在正确的位置添加括号来轻松纠正:
(not(True)) in [False, True] # prints true
writing: 写作:
not(True) in [False, True]
is the same like: 是这样的:
not((True) in [False, True])
which looks if True
is in the list and returns the "not" of the result. 看看True
是否在列表中并返回结果的“not”。
#4楼
Operator precedence 2.x , 3.x . 运算符优先级 2.x , 3.x 。 The precedence of not
is lower than that of in
. not
的优先级低于in
的优先级。 So it is equivalent to: 所以它相当于:
>>> not ((True) in [False, True])
False
This is what you want: 这就是你想要的:
>>> (not True) in [False, True]
True
As @Ben points out: It's recommended to never write not(True)
, prefer not True
. 正如@Ben所指出的那样:建议永远不要写not(True)
, not True
。 The former makes it look like a function call, while not
is an operator, not a function. 前者使它看起来像一个函数调用,而not
一个操作符,而不是一个函数。
#5楼
It is evaluating as not True in [False, True]
, which returns False
because True
is in [False, True]
它not True in [False, True]
评估not True in [False, True]
,返回False
因为True
在[False, True]
If you try 如果你试试
>>>(not(True)) in [False, True]
True
You get the expected result. 你得到了预期的结果。
#6楼
not x in y
is evaluated as x not in y
not x in y
中的x not in y
被评估为x not in y
You can see exactly what's happening by disassembling the code. 通过反汇编代码,您可以准确地看到发生了什么。 The first case works as you expect: 第一种情况按预期工作:
>>> x = lambda: False in [False, True]
>>> dis.dis(x)
1 0 LOAD_GLOBAL 0 (False)
3 LOAD_GLOBAL 0 (False)
6 LOAD_GLOBAL 1 (True)
9 BUILD_LIST 2
12 COMPARE_OP 6 (in)
15 RETURN_VALUE
The second case, evaluates to True not in [False, True]
, which is False
clearly: 第二种情况,评估为True not in [False, True]
,这是False
:
>>> x = lambda: not(True) in [False, True]
>>> dis.dis(x)
1 0 LOAD_GLOBAL 0 (True)
3 LOAD_GLOBAL 1 (False)
6 LOAD_GLOBAL 0 (True)
9 BUILD_LIST 2
12 COMPARE_OP 7 (not in)
15 RETURN_VALUE
>>>
What you wanted to express instead was (not(True)) in [False, True]
, which as expected is True
, and you can see why: 你要表达的是(not(True)) in [False, True]
中的(not(True)) in [False, True]
,正如预期的那样是True
,你可以看出原因:
>>> x = lambda: (not(True)) in [False, True]
>>> dis.dis(x)
1 0 LOAD_GLOBAL 0 (True)
3 UNARY_NOT
4 LOAD_GLOBAL 1 (False)
7 LOAD_GLOBAL 0 (True)
10 BUILD_LIST 2
13 COMPARE_OP 6 (in)
16 RETURN_VALUE