如何使用numpy.all()或numpy.any()? [英] How to use numpy.all() or numpy.any()?

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

问题描述

我正在尝试在2D numpy数组中搜索特定值,get_above方法返回字符'initial char'上方的坐标列表

I am trying to search in a 2D numpy array for a specific value, the get_above method returns a list of coordinates above the character 'initial char'

def get_above(current, wordsearch):
list_of_current_coords = get_coords_current(current, wordsearch)
#print(list_of_current_coords)
length = len(list_of_current_coords)
first_coords = []
second_coords = []
for x in range(length):
    second = list_of_current_coords[x][1]
    new_first = list_of_current_coords[x][0] - 1
    first_coords.append(new_first)
    second_coords.append(second)
combined = [first_coords, second_coords]
above_coords = []
for y in range(length):
    lst2 = [item[y] for item in combined]
    above_coords.append(lst2)   
return above_coords

def search_above(initial_char, target, matrix):
    above_coords = get_above(initial_char, matrix)
    length = len(above_coords)
    for x in range(length):
        if matrix[above_coords[x]] == target:
            print(above_coords[x])
        else:
            print('not found')

调用函数时出现此错误:

And I get this error when calling the function:

ValueError:具有多个元素的数组的真值不明确.使用a.any()或a.all()

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

任何帮助将不胜感激!

推荐答案

ValueError是由if语句中的数组比较引起的.

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)

m==3测试产生一个布尔数组.不能在if上下文中使用.

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

anyall可以将该数组压缩为一个标量布尔值:

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

所以在

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

查看matrix[above_coords[x]] == target,并准确确定应如何将其转换为标量True/False值.

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

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

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