python - 单个语句中的多个比较运算符(链接比较运算符)

标签 python

这是否符合我的想法?

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 to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < 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 to a 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/

相关文章:

python - 如何在机器人框架中保存对象状态

javascript - 如何在 10 个点后从图中删除旧数据点?

python - Threading Condition Acquire lock 并不是真正获取锁

python - 优雅的 python ?

python - 如何有效地迭代 Pandas 数据帧的连续 block

python - matplotlib 中的模糊圆圈和椭圆

python - 仅出于特定目的临时加载语言文件

python - 我可以安全删除 "/anaconda3/pkgs"中的文件吗?

python - Pandas:应用函数:TypeError:不支持的操作数类型 -: 'unicode' 和 'unicode'

python - SQLite3 序列类型没有增加