python从左至右,Python比较运算符从左到右链接/分组?

The Python documentation for operator precedence states:

Operators in the same box group left to right (except for

comparisons, including tests, which all have the same precedence and

chain from left to right — see section Comparisons...) [https://docs.python.org/2/reference/expressions.html#operator-precedence]

What does this mean? Specifically:

Q1: "Operators in the same box group left to right (except for

comparisons...)" -- do comparisons not group left to right?

Q2: If

comparisons do not group left to right, what do they do instead? Do

they "chain" as opposed to "group"?

Q3: If comparisons "chain"

rather than "group", what is the difference between "chaining" and

"grouping"?

Q4: What would be some examples to demonstrate that the comparison operators chain from left to right rather than from right to left?

解决方案

Grouping (this is what non-comparison operators do):

a + b + c means (a + b) + c

Chaining (this is what comparison operators do):

a < b < c means (a < b) and (b < c)

Grouping left to right (this is the way things are grouped):

5 - 2 - 1 means (5 - 2) - 1 == 2

as opposed to grouping right to left (this would produce a different result):

5 - (2 - 1) == 4

(edit)

Chaining is left to right, so in a < b < c, the expression a < b is evaluated before b < c, and if a < b is false, b < c is not evaluated.

(2 < 1 < nonsense) gives the value False because (1 < nonsense) is never evaluated.

(nonsense > 1 > 2) raises an error trying to evaluate (nonsense > 1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值