简体   繁体   English

在Python中内置函数all()和any()

[英]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. 它使用生成器理解基于原始数组对TrueFalse进行迭代。 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.

相关问题 python 中是否有任何内置函数来最小化所有 y 偏差平方的总和(最小二乘法)? - Is there any built-in function in python to minimize the sum of all y-deviations squared (Least-Square)? python中的any()all()函数 - any() all() function in python 大熊猫中是否有等效于内置函数all的python? - Is there an equivalent of the python built in function `all` in pandas? Python内置函数`all`和`any`的Perl pendant - Perl pendant for Python Built-in Functions `all` and `any` PHP应用程序是否有任何内置函数与python中的compile()相同? - Is there any Built in function for PHP Application same as compile() in python? Python 2 和 Python 3 内置的 all() 函数表现不一样 - Python 2 and Python 3 built-in all() function not behaving equally 是否有任何内置函数在Python中获取负整数的二进制格式? - Is there any built-in function to get the binary format of a negative integer in Python? 为什么在没有任何导出功能的情况下增强python构建 - Why boost python built library without any export function? 为什么 Python 内置的“all”函数为空的可迭代对象返回 True? - Why Python built in “all” function returns True for empty iterables? 返回语句列表中内置的所有函数的Python使用 - Python usage of built in all function on list in return statement
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM