鱼C论坛

 找回密码
 立即注册
查看: 1352|回复: 2

[已解决]关于一个表达式的运算过程

[复制链接]
发表于 2017-11-3 13:04:36 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
3>2>2最后输出的结果是False,它的运算过程是怎么样的呢?
最佳答案
2017-11-3 13:17:03


3>2>2
等价于
3>2 and 2>2
等价于
(3>2) and (2>2)

这就是所谓的“链式比较”。

这里有介绍:
- https://docs.python.org/3.6/reference/expressions.html
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).


- https://stackoverflow.com/questions/101268/hidden-features-of-python
  - https://stackoverflow.com/questions/101268/hidden-features-of-python#101945
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-11-3 13:16:42 | 显示全部楼层
python支持连续比较
内部会自动转换

比如
3>2>2 等价于:
3 > 2 and 2 > 2
返回 False

3>2>1 等价于:
3>2 and 2>1
返回True
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2017-11-3 13:17:03 | 显示全部楼层    本楼为最佳答案   


3>2>2
等价于
3>2 and 2>2
等价于
(3>2) and (2>2)

这就是所谓的“链式比较”。

这里有介绍:
- https://docs.python.org/3.6/reference/expressions.html
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).


- https://stackoverflow.com/questions/101268/hidden-features-of-python
  - https://stackoverflow.com/questions/101268/hidden-features-of-python#101945
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-3 15:29

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表