在Python中比较numpy数组的元素
我想比较两个1x3的数组,比如:
if output[x][y] != [150,25,75]
(这里的output
是一个3x3x3的数组,所以output[x][y]
实际上是一个1x3的数组).
我遇到了一个错误,错误信息是:
ValueError: The truth value of an array with more than one element is ambiguous.
这是不是意味着我需要这样做:
if output[y][x][0] == 150 and output[y][x][1] == 25 and output[y][x][2] == 75:
或者有没有更简单的方法来实现这个呢?
我使用的是Python v2.6
4 个回答
3
转换成一个列表:
if list(output[x][y]) != [150,25,75]
8
在使用numpy库时,可以用 np.allclose 这个方法来比较两个数组是否相近。
np.allclose(a,b)
不过如果你比较的是整数,
not (a-b).any()
那用这个方法会更快一些。
5
你还会看到这样的提示:
使用 a.any() 或 a.all()
这意味着你可以这样做:
if (output[x][y] != [150,25,75]).all():
这是因为比较两个数组或者一个数组和一个列表时,会得到一个布尔数组。就像这样:
array([ True, True, True], dtype=bool)