如何解释链接比较操作的抽象语法树? [英] How to explain the abstract syntax tree of chained comparison operations?
问题描述
比较运算符,例如 x< & z
应该给出(x< y)和(y< z)
的结果,除了 y
保证仅被评估一次。
Comparison operators can be chained in python, so that for example x < y < z
should give the result of (x < y) and (y < z)
, except that y
is guaranteed to be evaluated only once.
此操作的抽象语法树如下:
The abstract syntax tree of this operation looks like:
>>> ast.dump(ast.parse('0 < 1 < 2'), annotate_fields=0)
'Module([Expr(Compare(Num(0), [Lt(), Lt()], [Num(1), Num(2)]))])'
精美打印:
Module
Expr
Compare
Num
Lt
Lt
Num
Num
但它似乎被解析为 0< < 1 2
,但我不确定如何将其与 0< 1和1 < 2
。
But it seems to parse as something like 0 < < 1 2
and I'm not sure how to reconcile that with the logical result of something like 0 < 1 and 1 < 2
.
如何解释链式比较的ast?
How can the ast for chained comparisons be explained?
推荐答案
-- need sequences for compare to distinguish between
-- x < 4 < 3 and (x < 4) < 3
| Compare(expr left, cmpop* ops, expr* comparators)
如果将其作为两个单独的比较进行评估,例如
If it were evaluated as two separate compares, like this
Module(Expr(Compare(Compare(Num(0), [Lt()], [Num(1)]), [Lt()], [Num(2)]))])
然后实际上是将第一个比较的布尔值结果与第二个比较的整数进行比较。
Then it's actually comparing the boolean result of the first comparison with the integer in the second comparison.
类似的东西行不通
-5 < -4 < -3
因为它将被评估为
(-5 < -4) < -3
哪个评估为
1 < -3
因此,它作为单个表达式处理。 Compare
操作的python实现看起来像这样
So instead, it's dealt with as a single expression. A python implementation of the Compare
operation would look something like this
def Compare(left, ops, comparators):
if not ops[0](left, comparators[0]):
return False
for i, comparator in enumerate(comparators[1:], start=1):
if not ops[i](comparators[i-1], comparator):
return False
return True
这篇关于如何解释链接比较操作的抽象语法树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!