← 中文资源

简体中文版本

any 与 all 对生成器短路求值

any 命中第一个真值即停,all 撞上第一个假值即停;空输入 any 为 False、all 为 True,想知道具体是哪一条满足条件就用 next 加默认值。

阅读英文原文

运行结果

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

any([1,-2,3]):
  probing 1
True
all([1,-2,3]):
  probing 1
  probing -2
False
all([]) = True | any([]) = False
has paid order  : True
all orders paid : False
first paid order: {'total': 40}

实现说明

全部逻辑都在函数 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)