Python 通过链式比较做了一些特殊的事情。
以下是不同的评估:
x > y > z # in this case, if x > y evaluates to true, then
# the value of y is used, again, and compared with z
(x > y) > z # the parenthesized form, on the other hand, will first
# evaluate x > y. And, compare the evaluated result
# with z, which can be "True > z" or "False > z"
但是,在这两种情况下,如果第一个比较是False
,则不会查看语句的其余部分。
对于您的特定情况,
1 in [] in 'a' # this is false because 1 is not in []
(1 in []) in a # this gives an error because we are
# essentially doing this: False in 'a'
1 in ([] in 'a') # this fails because you cannot do
# [] in 'a'
同样为了演示上面的第一条规则,这些是评估为 True 的语句。
1 in [1,2] in [4,[1,2]] # But "1 in [4,[1,2]]" is False
2 < 4 > 1 # and note "2 < 1" is also not true
Python 运算符的优先级:https ://docs.python.org/3/reference/expressions.html#comparisons