gpt4 book ai didi

Python:numpy 数组列表,不能做 index()?

转载 作者:行者123 更新时间:2023-12-02 17:28:03 25 4
gpt4 key购买 nike

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数组?这是否与我在问题开头提到的错误有关?

最佳答案

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

>>> 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,这就是错误发生的时间。您可以编写自己的循环或先将所有数组转换为列表。

关于Python:numpy 数组列表,不能做 index()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36960830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com