这是否符合我的想法?
assert 1 < 2 < 3
我在 the docs 中找不到任何对此的引用但我看到它的代表很高answer .
它似乎有效,但也可能是运气好,就像最左边的解析为 True
,然后在另一个中使用 True
。
我做了一些测试,它总是按预期工作,但我想找到一个来源(文档)明确说明它的意图。
>>> 1<2<3<4<5
True
>>> 1<2<7<4<5
False
>>> 1<2<3>2<5
True
这排除了“最左边第一”的假设:
>>> 1<3<2
False
>>> (1<3)<2
True
最佳答案
这在Expressions中有详细记录。文档章节:
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then
a op1 b op2 c ... y opN z
is equivalent toa op1 b and b op2 c and ... y opN z
, except that each expression is evaluated at most once.Note that
a op1 b op2 c
doesn’t imply any kind of comparison between a and c, so that, e.g.,x < y > z
is perfectly legal (though perhaps not pretty).
关于python - 单个语句中的多个比较运算符(链接比较运算符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43677790/