【问题标题】:How to use numpy.all() or numpy.any()?如何使用 numpy.all() 或 numpy.any()?
【发布时间】:2016-11-26 16:59:59
【问题描述】:

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

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')

调用函数时出现此错误:

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

任何帮助将不胜感激!

【问题讨论】:

  • 能否也提供get_above的代码?
  • 无论如何,在您的if matrix[above_coords[x]] == target 行中,您可能会将矩阵中的整个 与一个目标值进行比较。 NumPy 告诉您,如果您想查看给定行中的 any 值是否计算为True,请使用array.any()。要使这些行计算为布尔值,您可以对给定的行尝试这样的操作:[True if value == target else False for value in row]
  • 使用示例案例并向我们展示预期的输出?

标签: python arrays numpy valueerror


【解决方案1】:

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

让我们做一个更简单的测试用例:

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 上下文中使用。

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

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 值。

【讨论】:

    猜你喜欢
    • 2015-09-11
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 2013-06-12
    相关资源
    最近更新 更多