且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么python`any`返回一个bool而不是值?

更新时间:2023-02-19 12:22:26

这个问题在2005年的Python开发者邮件列表中出现,当时Guido Van Rossum提出添加任何全部到Python 2.5。

This very issue came up up on the Python developer's mailing list in 2005, when Guido Van Rossum proposed adding any and all to Python 2.5.

Bill Janssen 请求它们被实现为

Bill Janssen requested that they be implemented as

def any(S):
    for x in S:
        if x:
            return x
    return S[-1]

def all(S):
    for x in S:
        if not x:
            return x
    return S[-1]

Raymond Hettinger,执行任何全部回覆专门解决为什么 any 全部不像

Raymond Hettinger, who implemented any and all, responded specifically addressing why any and all don't act like and and or:


随着时间的流逝,我收到了关于这些和其他itertools食谱的反馈。
没有人反对这些食谱中的True / False返回值或Guido版本中的

Over time, I've gotten feedback about these and other itertools recipes. No one has objected to the True/False return values in those recipes or in Guido's version.

Guido的版本与任何/所有的正常期望匹配为
谓词。此外,它避免了人们对
目前使用Python独特实现和和
或的错误/混淆。

Guido's version matches the normal expectation of any/all being a predicate. Also, it avoids the kind of errors/confusion that people currently experience with Python's unique implementation of "and" and "or".

回归最后一个元素不是邪恶的;这是奇怪的,意想不到的,
不明显。抵制这个棘手的冲动。

Returning the last element is not evil; it's just weird, unexpected, and non-obvious. Resist the urge to get tricky with this one.

邮件列表在很大程度上是同意的,让您今天看到的执行情况。

The mailing list largely concurred, leaving the implementation as you see it today.