【问题标题】:Python: List of numpy arrays, can't do index()?Python:numpy 数组列表,不能做 index()?
【发布时间】:2016-04-30 22:13:34
【问题描述】:

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

centers.index(shortest_dist[1])

它告诉我

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

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

请参阅以下演示。我无法理解发生了什么。

>>> 
>>> 
>>> 
>>> 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()
>>> 

所以查询a的索引是可以的,但是b的索引不行,虽然都是numpy数组?当问题开头提到我的错误时,这是​​否必须这样做?

【问题讨论】:

标签: python arrays list numpy


【解决方案1】:

当你比较数组时,你会得到一个数组。 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()

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

【讨论】:

  • d = [[1,2,3], [1,3,4],[4,5,6]] >>> d.index([4,5,6]) 2
  • 这没关系,所以问题只出在 numpy 数组列表上?
  • 换句话说,如果我有一个 numpy 数组列表,我就不能做 .index()?
  • @Jobs 是的,列表比较只返回布尔值。是的,您不能在数组列表上使用index。这确实表明数组没有正确实现==,因为它们违反了合同。
猜你喜欢
  • 1970-01-01
  • 2021-06-11
  • 2012-12-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多