Python 包含numpy数组的结构的相等性
众所周知,numpy数组上的Python 包含numpy数组的结构的相等性,python,numpy,Python,Numpy,众所周知,numpy数组上的==返回一个数组而不是bool,但这有时非常不方便 >>> [np.zeros(4)] == [np.zeros(4)] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: The truth value of an array with more than one element is a
==
返回一个数组而不是bool,但这有时非常不方便
>>> [np.zeros(4)] == [np.zeros(4)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>[np.zeros(4)]==[np.zeros(4)]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
ValueError:包含多个元素的数组的真值不明确。使用a.any()或a.all()
在我的例子中,我有一个巨大的嵌套dict、list等结构,其中偶尔包含numpy数组。它们可能包含numpy数组这一事实意味着
=
不能用于比较,因为它偶尔会抛出异常,所以我需要手动遍历它。这是缓慢的,冗长的,只是总体上令人讨厌。有更好的解决方法吗?在结构中有多少层嵌套?您是否尝试过all((a==b).all()如果是instance(a,np.ndarray)或者a==b表示zip(a,b)中的a,b)
?手动或内置Python代码中遍历结构的唯一捷径是测试相同的id
。