Why does “not(True) in [False, True]” return False?
如果我这样做:
1 2 | >>> False in [False, True] True |
返回
但如果我这样做:
1 2 | >>> not(True) in [False, True] False |
返回
1 2 | >>> not(True) False |
为什么?
算子值优先2.x of the值优先,3.x.
1 2 | >>> not (True in [False, True]) False |
是:这是你想要的P></
1 2 | >>> (not True) in [False, True] True |
"好点了。这是我的建议:
evaluated
你可以看到确切的说因为是怎么发生的disassembling by the队列。第一家工厂as the你期望:P></
1 2 3 4 5 6 7 8 | >>> 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 |
房屋evaluates to the second,
1 2 3 4 5 6 7 8 9 | >>> 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 >>> |
是你而不是我想表达
1 2 3 4 5 6 7 8 9 | >>> 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 |
算子值优先。
它的经营者(
1 | (not(True)) in [False, True] # prints true |
写作:P></
1 | not(True) in [False, True] |
is the same类:P></
1 | not((True) in [False, True]) |
如果which is in the list
如果你尝试P></
1 2 | >>>(not(True)) in [False, True] True |
You get the expected result。P></
alongside the answers of the other is that上述值优先
1 | not (True in [False, True]) |
但是,如果你不注意你的condition from the other酮单独使用,Python会角色(2
1 | (not True) in [False, True] |
但上述改性AS,there is another在线chaining that is by Python开发者:P></
基于Python的文档:P></
Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section.
for example of the following statement
1 2 | >>> True == False in [False, True] False |
因为Python会声明:the following链类P></
1 | (True == False) and (False in [False, True]) |
确切的说因为是
你可以承担,中央共享对象的操作和will be between 2其他对象(在这虚假的房屋)。P></
与已知的比较,也为其真正身份的会员,包括检验和试验及其操作数操作:which areP></
1 | in, not in, is, is not, <, <=, >, >=, !=, == |
实例:P></
1 2 | >>> 1 in [1,2] == True False |
另一个著名的example is number的范围:P></
1 | 7<x<20 |
which is equal to:P></
1 | 7<x and x<20 |
为了澄清其他一些答案,在一元运算符后添加括号不会改变其优先级。
要从另一个角度来看,请考虑
1 2 | >>> -2**2 -4 |
如果你想要负二的平方呢?很明显,你会加上括号:
1 2 | >>> (-2)**2 4 |
但是,不合理的做法是期望以下内容给予
1 2 | >>> -(2)**2 -4 |
因为
它让我们看到:检查操作系统,as a collection list is some
therefore