我想知道Python如何解析:
not a < b < c
它似乎将其解释为:
not (a < b < c)
与 (not a) < b < c
相反
这个问题解释了分组与链接: Python comparison operators chaining/grouping left to right?但是链式比较的优先级规则是什么?
我觉得很奇怪not
, <
和>
具有相同的优先级,但是 not a < b < c
解析为 not (a < b < c)
而-a < b < c
解析为 (-a) < b < c
.
我通过评估 not 2 > 1 > 2
来测试这一点在 Python 2.7 中。
最佳答案
Python 有一个抽象语法树模块来向您展示正在发生的事情:
import ast
t = ast.parse('not a < b < c')
print(ast.dump(t))
它给出了(清理了一下):
[Expr(value=UnaryOp(
op=Not(),
operand=Compare(
left=Name(id='a'),
ops=[Lt(), Lt()],
comparators=[Name(id='b'), Name(id='c')]
)
))]
事实上,documentation说not
优先级低于 <
.
关于python - 链式比较的优先级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46136618/