← 中文资源

简体中文版本

链式比较读起来像数学

Python 把链式比较当作一个表达式从左到右求值,中间操作数只求值一次:0 < x < 10 写起来像数学,行为也和数学一致,比 and 拼接更简洁。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

True False False
True
True
False
True

实现说明

真正干活的是函数 in_band,其余都是接线。

使用要点

  • in_band 是公开入口,文件里其余部分都是为它服务的内部实现。

常见问题

包管理器会看到什么?

一份空的依赖清单。示例没有需要抓取的导入。 文件在加载时定义 in_band。

主要签名是 def in_band(x)

核心语句

def in_band(x):
    return 0 < x < 10

代码示例

# 0 < x < 10 is one expression: each link compares the middle value once
def in_band(x):
    return 0 < x < 10

print(in_band(5), in_band(-1), in_band(10))

# Equivalent to: (0 < x) and (x < 10) — x is evaluated only once
x = 5
print((0 < x) and (x < 10))

# Chaining mixes operators and equality links
a, b, c = 1, 1, 2
print(a == b < c)
print(a < b < c)

# Strings order lexicographically in the same chained style
print("apple" < "banana" < "cherry")