[英]How do I determine if two lists of numpy arrays are equal
Suppose I have the following arrays:假设我有以下 arrays:
myarray1 = [np.array([1,2,3,4]),np.array([4,5,6]),np.array([7,8,9])]
myarray2 = [np.array([1,2,3,4]),np.array([4,5,6]),np.array([7,8,9])]
I get an error if I do the following:如果执行以下操作,我会收到错误消息:
myarray1==myarray2
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
My ultimate goal is to see if they are both exactly the same.我的最终目标是看看它们是否完全相同。 How can I do that?
我怎样才能做到这一点?
In [21]: alist1 = [np.array([1,2,3,4]),np.array([4,5,6]),np.array([7,8,9])]
...: alist2 = [np.array([1,2,3,4]),np.array([4,5,6]),np.array([7,8,9])]
In [22]: alist1==alist2
Traceback (most recent call last):
Input In [22] in <cell line: 1>
alist1==alist2
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Do a test like this:做这样的测试:
In [26]: [np.array_equal(a,b) for a,b in zip(alist1, alist2)]
Out[26]: [True, True, True]
In [27]: all(_)
Out[27]: True
list
equal checks for identical id
, and failing that for ==
. list
equal 检查相同的id
,失败则检查==
。 But ==
for arrays is elementwise, so doesn't produce a single value for each pair.但是 arrays 的
==
是逐元素的,因此不会为每一对生成单个值。 We have to work around that, getting a single True/False for each pair, and then combining those.我们必须解决这个问题,为每一对获取一个 True/False,然后将它们组合起来。
In [28]: [a==b for a,b in zip(alist1, alist2)]
Out[28]:
[array([ True, True, True, True]),
array([ True, True, True]),
array([ True, True, True])]
You can use np.array_equal(array1, array2)
for this.您可以为此使用
np.array_equal(array1, array2)
。
Alternatively, all(array1 == array2)
或者,
all(array1 == array2)
use .array_equal()
.使用
.array_equal()
。 But you need to be careful as you have a list of numpy arrays.但是你需要小心,因为你有一个列表 numpy arrays。
import numpy as np
myarray1 = [np.array([1,2,3,4]),np.array([4,5,6]),np.array([7,8,9])]
myarray2 = [np.array([1,2,3,4]),np.array([4,5,6]),np.array([7,8,9])]
np.array_equal(myarray1[0], myarray2[0])
True
but但
np.array_equal(myarray1, myarray2)
False
@hpailj has the solution though for you above. @hpailj 在上面为您提供了解决方案。 So accept that solution.
所以接受那个解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.