Python:numpy数组列表,不能执行index()吗?

Job*_*obs 4 python arrays numpy list

center 是 numpy 数组的列表 [ ]。Shortest_dist[1] 是一个 numpy 数组。但是,当我这样做时:

centers.index(shortest_dist[1])
Run Code Online (Sandbox Code Playgroud)

它告诉我

 ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Run Code Online (Sandbox Code Playgroud)

这很奇怪,所以我尝试了以下方法:

请参阅以下演示。我无法理解正在发生的事情。

>>> 
>>> 
>>> 
>>> a = np.asarray([1,2,3,4,5])
>>> b = np.asarray([2,3,4,5,6])
>>> c = []
>>> c.append(a)
>>> c.append(b)
>>> c.index(a)
0
>>> c.index(c[0])
0
>>> c.index(c[1])
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()
>>> c.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()
>>> len(c)
2
>>> c[1]
array([2, 3, 4, 5, 6])
>>> b
array([2, 3, 4, 5, 6])
>>> c.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()
>>> 
Run Code Online (Sandbox Code Playgroud)

那么查询 a 的索引是可以的,但不能查询 b 的索引,尽管两者都是 numpy 数组?这是否与问题开头提到的我的错误有关?

Ale*_*all 7

当您比较数组时,您会得到一个数组。Numpy 拒绝将这些比较的结果解释为布尔值。

>>> c[0] == c[0]
array([ True,  True,  True,  True,  True], dtype=bool)
>>> bool(c[0] == c[0])
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()
Run Code Online (Sandbox Code Playgroud)

的实现index是检查此类比较以找到要返回的索引。据推测,它有一个优化,首先检查身份相等性,这就是为什么c.index(a)不会引发错误。但在c.index(b)它必须检查if a == b时,就会发生错误。您可以编写自己的循环或先将所有数组转换为列表。

  • 换句话说,如果我有一个 numpy 数组列表,我就不能执行 .index() ? (2认同)
  • @Jobs是的,列表比较只返回布尔值。是的,您不能在数组列表上使用“index”。实际上,这表明数组没有正确实现“==”,因为它们违反了约定。 (2认同)