python多维数组索引,查找数组的索引在Python 2多维数组

I have an array

v = (x,y,z)

and two multidimensional array

l = (a,b,c),(d,e,f)

and

r = (g,h,i),(l,m,n),(x,y,z).

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:

Index 0 is out of bounds for axis 0 with size 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?

解决方案

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.

Update:

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值