关于list 数据类型 和 ndarray 数据类型获取索引的小坑

今天在写代码的时候,遇到了这个问题AttributeError: 'numpy.ndarray' object has no attribute 'index'。上网查找后发现list和ndarray数据结构是有很大区别的,list结构可以通过index获取元素的索引,而ndarray是没有的,因此,我们若想获得同样的功能,那么就必须將ndarray转换成list,不然就要另寻其他的方法了,这里我们利用tolist()函数来实现二者转换。

那么机智的你一定会想到,我用一个新的变量来承接变换后的list数据结构不行么,例,我有一个二位数组ndarray  bound,那么我这样,

tran = [ ]

tran = bound.tolist( )

如果你接下来的代码功能是这样的:

for a in bound:

    index = tran.tolist()

print (index)

很遗憾,这样做的话,你八成会产生以下的报错:ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()。因为这样用的话,只是将bound转换后赋给了tran,但是遍历的时候用的元素仍然是bound中的元素,所以会报错。

上网查找了问题所在,这篇文章写的相对详细https://blog.csdn.net/sinat_33563325/article/details/79868109

因此我们这样用:

bound = bound.tolist()直接将bound的数据类型给修改了,就好啦。

发布了36 篇原创文章 · 获赞 4 · 访问量 8051

猜你喜欢

转载自blog.csdn.net/qq_41368074/article/details/103110512