有人可以解释为什么会发生以下情况吗?我的用例是我有一个 python 列表,它的元素都是 numpy ndarray 对象,我需要搜索列表以找到特定 ndarray obj 的索引。
最简单的例子:
>>> import numpy as np
>>> a,b = np.arange(0,5), np.arange(1,6)
>>> a
array([0, 1, 2, 3, 4])
>>> b
array([1, 2, 3, 4, 5])
>>> l = list()
>>> l.append(a)
>>> l.append(b)
>>> l.index(a)
0
>>> l.index(b)
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()
为什么可以
l
找到 a
的索引,但不是 b
?
最佳答案
应用 https://stackoverflow.com/a/17703076/901925 中的想法(参见相关边栏)
[np.array_equal(b,x) for x in l].index(True)
应该更可靠。它确保了正确的数组到数组的比较。
或
[id(b)==id(x) for x in l].index(True)
如果你想确保它比较 id。
关于list - 在列表中查找numpy数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30331919/