📜  Python中的链接运算符

📅  最后修改于: 2022-05-13 01:55:47.977000             🧑  作者: Mango

Python中的链接运算符

检查两个以上的条件在编程语言中很常见。假设我们要检查以下条件:

a < b < c

最常见的语法如下:

if a < b and b < c :
   {...}

在Python中,有一种更好的方法可以使用运算符Chaining来编写它。运算符的链接可以写成如下:

if a < b < c :
    {.....}

根据Python中的关联性和优先级, Python中的所有比较操作具有相同的优先级,低于任何算术、移位或按位操作。同样与 C 不同的是,像 a < b < c 这样的表达式具有数学中的常规解释。

Python中的运算符列表:

">" | "<" | "==" | ">=" | "<=" | "!=" | "is" ["not"] | ["not"] "in"

比较运算符中的链接:

  1. 比较产生布尔值:True 或 False。
  2. 比较可以任意链接。例如:
    x < y <= z is equivalent to x < y and y <= z, 

    除了 y 只被评估一次。
    (但在这两种情况下,当 x < y 被发现为假时,根本不会评估 z)。

  3. 形式上,如果 a, b, c, ..., y, z 是表达式并且 op1, op2, ..., opN 是运算符,那么 a op1 b op2 c ... y opN z 等价于 a op1 b and b op2 c and ... y opN z,除了每个表达式最多计算一次。
  4. 还,
    a op1 b op2 c 

    并不意味着 a 和 c 之间有任何比较,所以

    a < b > c

    是完全合法的。

# Python code to illustrate
# chaining comparison operators
x = 5
print(1 < x < 10)
print(10 < x < 20 )
print(x < 10 < x*10 < 100)
print(10 > x <= 9)
print(5 == x > 4)

输出:

True
False
True
True
True

另一个例子:

# Python code to illustrate
# chaining comparison operators
a, b, c, d, e, f = 0, 5, 12, 0, 15, 15
exp1 = a <= b < c > d is not e is f
exp2 = a is d > f is not c
print(exp1)
print(exp2)

输出:

True
False

参考: Python 3 文档