我有一个列表,其中的元素是这样的数组:
([1,2,3],[4,5,6],[7,8,9])
我想要的是在这个列表中找到一个元素的索引,比如:
list.index([4,5,6]) #should return 1.
问题是 numpy
数组比较会抛出错误,除非你输入类似:(A==B).all()
但是这个比较在索引函数中,所以我不能也不想在函数中添加all()
位。有更简单的解决方案吗?
最佳答案
您的最后一条错误消息表明您仍在混合使用列表和数组。我将尝试重现这种情况:
制作列表列表。查找子列表工作得很好:
In [256]: ll=[[1,2,3],[4,5,6],[7,8,9]]
In [257]: ll.index([4,5,6])
Out[257]: 1
从中创建一个数组 - 它是 2d。
In [258]: la=np.array(ll)
In [259]: la
Out[259]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
它没有索引方法
In [260]: la.index([4,5,6])
...
AttributeError: 'numpy.ndarray' object has no attribute 'index'
把它列成一个列表——但是我们得到了你的 ValueError:
In [265]: list(la).index([4,5,6])
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
那是因为 list(la)
返回一个数组列表,而数组在 ==
表达式中产生多个值:
In [266]: list(la)
Out[266]: [array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])]
从数组生成列表的正确方法是 tolist
,它返回原始的 ll
列表列表:
In [267]: la.tolist().index([4,5,6])
Out[267]: 1
关于python查找列表中数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33314398/