为什么python`any`返回一个bool而不是值? [英] Why does python `any` return a bool instead of the value?

查看:147
本文介绍了为什么python`any`返回一个bool而不是值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

返回他们评估的最后一个元素,但为什么Python的内置函数任何

and and or return the last element they evaluated, but why doesn't Python's built-in function any?

我的意思是这样实现自己很容易,但我仍然想知道为什么。 / p>

I mean it's pretty easy to implement oneself like this, but I'm still left wondering why.

def any(l):
    for x in l:
        if x:
            return x
    return x

编辑:

要添加以下答案,以下是关于这个问题的你们强大皇帝的同一个邮件列表的实际引用:

To add to the answers below, here's an actual quote from that same mailing list of ye mighty emperor on the issue:


是否总是返回True和False或第一个faling / pass
元素?我也在博客之前玩过,并意识到
的最终案例(如果序列为空或者所有元素都没有通过测试)
永远不会令人满意:pick None感觉很奇怪,如果
参数是一个可以迭代的bools,如果
的参数是一个非bool对象的迭代,则选择False会感到奇怪。

Whether to always return True and False or the first faling / passing element? I played with that too before blogging, and realized that the end case (if the sequence is empty or if all elements fail the test) can never be made to work satisfactory: picking None feels weird if the argument is an iterable of bools, and picking False feels weird if the argument is an iterable of non-bool objects.

Guido van Rossum (主页: http://www.python.org/~guido/

Guido van Rossum (home page: http://www.python.org/~guido/)


推荐答案

这个问题在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.

这篇关于为什么python`any`返回一个bool而不是值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆