python - 链式比较的优先级?

标签 python

我想知道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')]
    )
))]

事实上,documentationnot优先级低于 < .

关于python - 链式比较的优先级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46136618/

相关文章:

python - 将日期解析为从 csv 到 pandas 的字符串

python - 如何以优雅的方式处理复杂的 URL?

python - 单击 python GTK3 中的按钮后窗口卡住

python - 将 BeautifulSoup ResultSet 转换为字符串列表

python - 应该使用哪个版本的 Python?

python - 如何将 JSON 日期和时间转换为 Python 日期时间?

python - Elastic BeanSTAlk CLI 安装错误

python "TypeError: ' numpy.float6 4' object cannot be interpreted as an integer"

python - 如何使用 Python APT 标记特定的 conffile 以进行覆盖?

python - 如何解决python硬编码字典编码问题