Python“全部"有条件生成器表达式返回True的函数.为什么? [英] Python "all" function with conditional generator expression returning True. Why?

查看:129
本文介绍了Python“全部"有条件生成器表达式返回True的函数.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以帮助我理解为什么以下Python脚本返回True吗?

Can anyone help me understand why the following Python script returns True?

x = ''
y = all(i == ' ' for i in x)
print(y)

我想这与x是一个零长度的实体有关,但不能完全理解.

I imagine it's something to do with x being a zero-length entity, but cannot fully comprehend.

推荐答案

all()始终返回True ,除非序列中有一个元素为False.

all() always returns True unless there is an element in the sequence that is False.

您的循环产生0个项目,因此返回True.

Your loop produces 0 items, so True is returned.

已记录:

如果 iterable 的所有元素都为true(或iterable为空),则返回True.

Return True if all elements of the iterable are true (or if the iterable is empty).

强调我的.

类似地, any() 始终返回False除非,序列中的元素为True,所以对于空序列,any()返回默认值:

Similarly, any() will always return False, unless an element in the sequence is True, so for empty sequences, any() returns the default:

>>> any(True for _ in '')
False

这篇关于Python“全部"有条件生成器表达式返回True的函数.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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