How to use numpy.all() or numpy.any()?

丶灬走出姿态 提交于 2019-12-06 05:02:06

The ValueError is caused by an array comparison in the if statement.

Lets make a simpler test case:

In [524]: m=np.arange(5)
In [525]: if m==3:print(m)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-525-de75ce4dd8e2> in <module>()
----> 1 if m==3:print(m)

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
In [526]: m==3
Out[526]: array([False, False, False,  True, False], dtype=bool)

The m==3 test produces a boolean array. That can't be used in an if context.

any or all can condense that array into one scalar boolean:

In [530]: (m==3).any()
Out[530]: True
In [531]: (m==3).all()
Out[531]: False

So in

if matrix[above_coords[x]] == target:
        print(above_coords[x])

look at matrix[above_coords[x]] == target, and decide exactly how that should be turned into a scalar True/False value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!