问题描述
我有一个数组
v = (x,y,z)
和两个多维数组
l = (a,b,c),(d,e,f)
和
r = (g,h,i),(l,m,n),(x,y,z).
我想知道诉指数无论是第一或第二多维数组中为止。我试图
numpy.where(V = = L)[0] [0]
但它返回:
I want to know the index of
v
no matter if is in the first or second multidimensional array. I tried numpy.where(v==l)[0][0]
but it returns:
0指数超出范围轴0与0号。
工作,如果我在那里我有搜索指数矩阵前知道,但我不知道。谢谢
Works only if I know before the matrix where I have to search the Index, but I don't. Thanks
如果我想知道索引包含它的阵列?
And If I want to know the index and the array that contains it?
推荐答案
定义在要搜索接受要搜索的项目的功能和排列的列表,并使用循环来找到每个阵列中的项目。使用异常处理赶上
IndexError
。
Define a function that accepts the item to be searched and the list of array to be searched in and use a loop to find that item in each array. Use exception handling to catch the
IndexError
.
>>> import numpy as np
>>> v = np.array([[1, 2, 3]])
>>> r = np.array([[1, 2, 3], [0, 9, 8], [2, 4, 4]])
>>> l = np.array([[4, 5, 6], [7, 8, 9]])
def get_index(seq, *arrays):
for array in arrays:
try:
return np.where(array==seq)[0][0]
except IndexError:
pass
...
>>> get_index(v, r, l)
0
>>> get_index(np.array([7, 8, 9]), r, l)
1
您会得到
无
,如果该项目没有在任何阵列的输出发现
You'd get
None
as output if the item is not found in any of the array.
更新:
如果你想要的名称以及再通过阵列中的字典:
If you want the name as well then pass the arrays in a dictionary:
def get_index(seq, **arrays):
for name, array in arrays.items():
try:
return name, np.where(array==seq)[0][0]
except IndexError:
pass
...
>>> get_index(v, **dict(r=r, l=l))
('r', 0)
>>> get_index(np.array([7, 8, 9]), **dict(r=r, l=l))
('l', 1)
这篇关于查找数组的索引在Python 2多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!