代码之家  ›  专栏  ›  技术社区  ›  nonagon

链式比较的优先级?

  •  2
  • nonagon  · 技术社区  · 7 年前

    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中。

    1 回复  |  直到 7 年前
        1
  •  3
  •   John Zwinck    7 年前

    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 < .