在Python中二维数组中的索引处查找值

在Python中二维数组中的索引处查找值,python,arrays,list,numpy,Python,Arrays,List,Numpy,我有一个2D数组大小(2,3)和一个列表 输入: a=['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck'] b=[[4 2 8][1 7 0]] #2D numpy array shape (2,3) containing indices of list a c = [['deer','bird','ship'],['automobile','horse','airplane']]

我有一个2D数组大小(2,3)和一个列表

输入:

a=['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck']

b=[[4 2 8][1 7 0]] #2D numpy array shape (2,3) containing indices of list a
c = [['deer','bird','ship'],['automobile','horse','airplane']]
输出:

a=['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck']

b=[[4 2 8][1 7 0]] #2D numpy array shape (2,3) containing indices of list a
c = [['deer','bird','ship'],['automobile','horse','airplane']]
是否有任何pythonic方法或快捷方式来实现输出,而无需迭代每个索引值

这样做:

a=['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck']
b=numpy.array([[4,2,8],[1,7,0]])


c = [[a[idx] for idx in row] for row in b]
这就是工作:

a=['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck']
b=numpy.array([[4,2,8],[1,7,0]])


c = [[a[idx] for idx in row] for row in b]

如果您将列表也设为
np.array
,则只需
a[b]

>>> import numpy as np
>>> keys = np.array(['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck'])
>>> indices = np.array([[4,2,8],[1,7,0]])
>>> keys[indices]
array([['deer', 'bird', 'ship'],
       ['automobile', 'horse', 'airplane']], 
      dtype='<U10')
>>将numpy作为np导入
>>>keys=np.数组([“飞机”,“汽车”,“鸟”,“猫”,“鹿”,“狗”,“青蛙”,“马”,“船”,“卡车])
>>>索引=np.数组([[4,2,8],[1,7,0]]
>>>键[索引]
数组(['deer','bird','ship'],
[‘汽车’、‘马’、‘飞机’],

dtype='如果您将列表也设为一个
np.array
,则只需
a[b]

>>> import numpy as np
>>> keys = np.array(['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck'])
>>> indices = np.array([[4,2,8],[1,7,0]])
>>> keys[indices]
array([['deer', 'bird', 'ship'],
       ['automobile', 'horse', 'airplane']], 
      dtype='<U10')
>>将numpy作为np导入
>>>keys=np.数组([“飞机”,“汽车”,“鸟”,“猫”,“鹿”,“狗”,“青蛙”,“马”,“船”,“卡车])
>>>索引=np.数组([[4,2,8],[1,7,0]]
>>>键[索引]
数组(['deer','bird','ship'],
[‘汽车’、‘马’、‘飞机’],

dtype='您将如何处理输出?可能有更好的方法来表示您的数据。如果a在数组中转换,则它只是a[b]。为什么“不迭代每个索引值”?有没有充分的理由限制此限制?您可以使用
np.take
将二维数组作为输出:
np.take(a,b)
@tadhgmdonald Jensen在对numpy数组进行多次操作后,我得到了数组b。另外,数组b的形状为(n,3)其中n非常大,超过100000。因此我担心使用循环进行迭代所需的时间。但是numpy操作肯定会花费更少的时间。您将如何处理输出?可能有更好的方法来表示您的数据。如果a在数组中转换,则仅为a[b]。为什么“不迭代每个索引值”你可以使用
np.take
将一个2D数组作为输出:
np.take(a,b)
@tadhgmdonald Jensen我在numpy数组上进行了多次操作后得到了数组b。数组b也是有形状的(n,3)其中n非常大,超过100000。因此我担心使用循环进行迭代所需的时间。但是numpy操作肯定会花费更少的时间。这会在每个索引上进行迭代。@gr1zzlybe4r,因为
b
是一个必须遍历和索引的列表。这就是列表的全部要点。我希望将数组b保留为numpy数组以备将来使用为我的code@Kapes我已经编辑了我的答案,使b成为一个numpy数组。这不会改变代码的其余部分。但我不明白您想要什么,或者为什么这是不可接受的。如果可以的话,我很乐意提供帮助。@ColinDickie看到这会在每个索引上迭代。@gr1zzlybe4r好吧,因为
b
是一个必须遍历和索引的列表。这就是e列表的整点。我希望将数组b保留为numpy数组,以便为我的code@Kapes我已经编辑了我的答案,使b成为一个numpy数组。这不会改变代码的其余部分。但我对你想要什么,或者为什么这不被接受感到困惑。如果可以的话,我很乐意提供帮助。@ColinDickie