in和比较的python运算符优先级

in和比较的python运算符优先级,python,Python,以下比较产生True: >>> '1' in '11' True >>> ('1' in '11') == True True 用括号换一种方式,我得到一个类型错误: >>> '1' in ('11' == True) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: argument of type

以下比较产生
True

>>> '1' in '11'
True
>>> ('1' in '11') == True
True
用括号换一种方式,我得到一个类型错误:

>>> '1' in ('11' == True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable

Python手册中说,中的
==
的作用是相同的。因此,默认情况下,它们是从左到右进行评估的,但也需要考虑链接。您在上面输入的表达式('11'中的
'1==True
)实际上被计算为

('1' in '11') and ('11' == True)
这当然是
False
。如果你不知道什么是链接,它允许你做一些事情,比如

if 0 < a < 1:
如果0

在Python中,这意味着您所期望的(“a大于0但小于1”)。

它与优先级无关。在Python关系运算符链中,包含被视为关系运算符。因此:

'1' in '11' == True
同:

('1' in '11') and ('11' == True)
这是错误的,因为
True
不等于“11”。

这里发生了什么

'1' in '11' == True  ==>  False
这与:

'1' in ('11' == True)
但是

未定义。

允许您写入
x
,并表示
x
。看看这种互动:

>>> (False == True) == False
True
>>> False == (True == False)
True
>>> False == True == False
False
>>>
因此,在您的示例中,'11'中的
'1==True
相当于
('11'中的'1')和('11'==True)

('11' == True) ==> False
'1' in False
>>> (False == True) == False
True
>>> False == (True == False)
True
>>> False == True == False
False
>>>