Python中numpy数组元素的比较

2024-04-29 06:33:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想比较两个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


Tags: andoftheanoutputifvaluemore
3条回答

转换为列表:

if list(output[x][y]) != [150,25,75]

新方法是使用np.allclose

np.allclose(a,b)

尽管对于整数

not (a-b).any()

更快。

您还应该得到消息:

Use a.any() or a.all()

这意味着您可以执行以下操作:

if (output[x][y] != [150,25,75]).all():

这是因为两个数组或一个数组与一个列表的比较产生一个布尔数组。类似于:

array([ True,  True,  True], dtype=bool)

相关问题 更多 >