实现说明
全部逻辑都在函数 probe中。
使用要点
- 演示输出是带标签的(
probing、any([1,-2,3]):、all([1,-2,3]):),每个操作都会留下自己的一行标注。 - 把
probe当作 API:导入它,其余代码可以忽略。
常见问题
依赖情况复杂吗?
一点也不复杂:零依赖,没有要锁版本或审计的东西。 文件在加载时定义 probe。
主要签名是 def probe(n)
核心语句
def probe(n):
print(" probing", n)
return n > 0
代码示例
# any / all 都是短路求值:结论确定就停止消费迭代器
def probe(n):
print(" probing", n)
return n > 0
print("any([1,-2,3]):")
print(any(probe(n) for n in [1, -2, 3])) # 命中 1 即停
print("all([1,-2,3]):")
print(all(probe(n) for n in [1, -2, 3])) # 撞上 -2 即停
print("all([]) =", all([]), "| any([]) =", any([])) # 空值: all 真, any 假
# 生成器表达式直接在调用里写条件,不必先建列表
orders = [{"total": 0}, {"total": 40}, {"total": 120}]
print("has paid order :", any(o["total"] > 0 for o in orders))
print("all orders paid :", all(o["total"] > 0 for o in orders))
# 想知道"是哪一条"而不是"有没有",用 next + 默认值
first = next((o for o in orders if o["total"] > 0), None)
print("first paid order:", first)