如何将数组与数组列表进行比较?

Oma*_*idi 5 python arrays numpy list python-3.x

假设我有一个包含一堆numpyndarrays(甚至torch张量)的列表:

a, b, c = np.random.rand(3, 3), np.random.rand(3, 3), np.random.rand(3, 3)
collection = [a, b, c]
Run Code Online (Sandbox Code Playgroud)

现在,如果我要检查数组b是否在collection(假设我不知道数组中存在什么collection),然后尝试:b in collection吐出以下错误:

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

这同样适用于包含数组的元组。

解决此问题的一种方法是进行列表理解:

True in [(b == x).all() for x in collection]
Run Code Online (Sandbox Code Playgroud)

但是,这需要一个for循环,我想知道是否有更“有效”的方法来实现这一点?

Oma*_*idi 1

好吧,这比预期简单得多......

您实际上可以将数组/张量堆叠到更高的维度(在本例中为深度/通道),然后得到的数组是所有其他数组的集合,但独立存储在“不同的维度”中。

a, b, c = np.random.rand(3, 3), np.random.rand(3, 3), np.random.rand(3, 3)
collection = np.stack((a, b, c))
Run Code Online (Sandbox Code Playgroud)

现在您可以简单地检查bin collection,就像将其与列表进行比较一样:

b in collection
> True
Run Code Online (Sandbox Code Playgroud)