python 运算符优先级 in 和比较 [英] python operator precedence of in and comparison
问题描述
以下比较产生True
:
用括号反之,我得到一个类型错误:
<预><代码>>>>'1' in ('11' == True)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:bool"类型的参数不可迭代那么如何获得没有括号的 False
?
Python 手册说 in
和 ==
是相同的 优先级.因此,默认情况下从左到右评估它们,但也需要考虑链接.您上面的表达式('1' in '11' == True
)实际上被评估为...
('11' 中的'1') and ('11' == True)
当然是False
.如果您不知道什么是链接,那么它可以让您执行诸如...
如果 0 <<1:
在 Python 中,这意味着您所期望的(a 大于 0 但小于 1").
The following comparisons produce True
:
>>> '1' in '11'
True
>>> ('1' in '11') == True
True
And with the parentheses the other way, I get a TypeError:
>>> '1' in ('11' == True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable
So how do I get False
with no parentheses?
>>> '1' in '11' == True
False
The Python manual says in
and ==
are of equal precedence. Thus, they're evaluated from left to right by default, but there's also chaining to consider. The expression you put above ('1' in '11' == True
) is actually being evaluated as...
('1' in '11') and ('11' == True)
which of course is False
. If you don't know what chaining is, it's what allows you to do something like...
if 0 < a < 1:
in Python, and have that mean what you expect ("a is greater than 0 but less than 1").
这篇关于python 运算符优先级 in 和比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!