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

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

问题描述

x = np.arange(0,2,0.5)价值 = 2*x如果价值 <= 0.6:打印(这有效")别的:打印(价值太高")

这是我得到的错误:

如果值 <= 0.6:ValueError:包含多个元素的数组的真值不明确.使用 a.any() 或 a.all()

我已经阅读了几篇关于 a.any() 或 a.all() 的帖子,但仍然找不到真正清楚地解释如何解决问题的方法.我明白为什么 Python 不喜欢我写的东西,但我不知道如何解决它.

解决方案

如果你看一下 valeur <= 0.6 的结果,你就会明白是什么导致了这种歧义:

<预><代码>>>>价值 <= 0.6数组([真,假,假,假],dtype=bool)

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

这正是 numpy.anynumpy.all 所做的.前者要求至少有一个真值,后者要求所有值都为真:

<预><代码>>>>np.any(价值 <= 0.6)真的>>>np.all(价值 <= 0.6)错误的

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

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

here is the error I get:

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

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.

解决方案

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)

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?

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天全站免登陆