【发布时间】: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数组?当问题开头提到我的错误时,这是否必须这样做?
【问题讨论】:
-
@ppperry:如果这可能是该帖子的重复,您能否通过阅读该帖子来判断我上面的演示和代码中的问题是什么?是什么导致了问题以及如何解决?
-
这个
ValueError意味着一个布尔数组被用在一个需要一个标量布尔值的上下文中——一个if或者这里是一个列表index或compare。