Python:numpy数组列表,不能做index()吗? [英] Python: List of numpy arrays, can't do index()?

查看:558
本文介绍了Python:numpy数组列表,不能做index()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

centers is a list, [ ], of numpy arrays. shortest_dist[1] is an numpy array. However, when I do:

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

这很奇怪,所以我尝试了以下操作:

This is weird, so I tried the following things:

请参阅以下演示.我不知道发生了什么.

See the following demo. I cannot make sense of what's happening.

>>> 
>>> 
>>> 
>>> 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数组?问题开头提到我的错误时,是否必须这样做?

So it's okay to query the index of a, but not b, although both are numpy arrays? Does this have to do when my error, which is mentioned at the beginning of the question?

推荐答案

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

When you compare arrays, you get an array. Numpy is refusing to interpret the results of those comparisons as a boolean.

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

The implementation of index is checking such comparisons to find the index to return. Presumably it has an optimisation which checks for identity equality first which is why c.index(a) doesn't raise an error. But in c.index(b) it has to check if a == b and that's when the error happens. You can write your own loop or convert all the arrays to lists first.

这篇关于Python:numpy数组列表,不能做index()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆