[英]Built in function all() and any() in Python
I'm having trouble with the built-in functions of all(). 我在使用all()的内置函数时遇到了麻烦。 The code below should print 'fail' but instead gives me a 'success'.
下面的代码应该显示“失败”,但是却给我“成功”。 Could anyone tell me why this happens?
谁能告诉我为什么会这样?
test = np.array([9.,-1.,2.,3.,5.])
if test[:].all() > 0.:
print 'success'
else:
print 'fail'
As others mentioned in comments, all()
is a boolean function, so it's just looking if all elements are not 0 (aka False
). 就像其他评论中提到的那样,
all()
是一个布尔函数,因此它只是在查找所有元素是否都不为0(即False
)。
This is how you want to be using all()
for your specific case. 这就是您要针对特定情况使用
all()
的方式。 It uses a generator comprehension to make an iterable of True
and False
based on the original array. 它使用生成器理解基于原始数组对
True
和False
进行迭代。 It will return False
if any element is less than or equal to zero. 如果任何元素小于或等于零,它将返回
False
。
all(i > 0 for i in test)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.