使用a.any()或a.all() [英] Use a.any() or a.all()

查看:281
本文介绍了使用a.any()或a.all()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

x = np.arange(0,2,0.5)
valeur = 2*x

if valeur <= 0.6:
    print ("this works")
else:   
    print ("valeur is too high")

这是我得到的错误:

if valeur <= 0.6:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我已经阅读了几篇有关a.any()或a.all()的文章,但仍然找不到真正清楚地说明如何解决问题的方法.我明白了为什么Python不喜欢我写的内容,但是我不确定如何修复它.

I have read several posts about a.any() or a.all() but still can't find a way that really clearly explain how to fix the problem. I see why Python does not like what I wrote but I am not sure how to fix it.

推荐答案

如果查看valeur <= 0.6的结果,您会发现是什么导致这种歧义:

If you take a look at the result of valeur <= 0.6, you can see what’s causing this ambiguity:

>>> valeur <= 0.6
array([ True, False, False, False], dtype=bool)

因此,结果是在这种情况下具有4个布尔值的另一个数组.现在的结果是什么?当一个值为真时,条件是否为真?仅当所有值都为真时,条件才为真吗?

So the result is another array that has in this case 4 boolean values. Now what should the result be? Should the condition be true when one value is true? Should the condition be true only when all values are true?

numpy.anynumpy.all正是这样.前者至少需要一个真实值,而后者则需要所有真实值:

That’s exactly what numpy.any and numpy.all do. The former requires at least one true value, the latter requires that all values are true:

>>> np.any(valeur <= 0.6)
True
>>> np.all(valeur <= 0.6)
False

这篇关于使用a.any()或a.all()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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