当使用帮助(All)时,它返回:
all(iterable)=>bool
return True if bool(x) is True for all values x in the iterable.
if the iterable is empty, return True帮助(Bool)返回:
bool(x) -> bool
|
| Returns True when the argument x is true, False otherwise.
| The builtins True and False are the only two instances of the class bool.
| The class bool is a subclass of the class int, and cannot be subclassed.在尝试时:
>>>bool()
False
>>>all([])
True我的问题是,如果所有的输入都是空列表/dict/tuple(即迭代器),那么传递给bool的是什么??为什么它会返回True,因为它依赖于bool?
发布于 2014-06-26 04:56:02
如果bool()的参数是空的,则不会调用all(),这就是为什么文档将all()的行为作为一个特例在空输入上指出。
bool() == False的行为与all()在任何情况下所做的都无关。顺便说一句,在Python中,bool是int的一个子类,因此bool() == False必须与该int() == 0兼容。
至于为什么all([])是True,这是为了保留有用的身份。最重要的是,对于任何非空序列x来说,
all(x) == (bool(x[0]) and all(x[1:]))all([]) == True是唯一允许x的所有值都保持身份的结果。
发布于 2014-06-26 04:51:52
all(iterable)...is 记录在案等价于;
def all(iterable):
for element in iterable:
if not element:
return False
return True只有当列表中的任何值转换为False时,...which才返回False。
由于您传入的列表中没有元素,所以没有任何元素转换为False,函数调用的结果是True。
发布于 2014-06-26 04:44:50
…是怎么回事?
什么都没有--也没有bool()的“无”。bool从未被调用过。空序列中的每个元素都是真实的吗?是!毕竟,没有什么是不可能的。
https://stackoverflow.com/questions/24422510
复制相似问题