在Python的2D数组中查找索引的值

2024-05-11 14:44:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个二维数组大小(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']]

有没有什么方法或快捷方式可以在不迭代每个索引值的情况下实现输出?你知道吗


Tags: numpy列表数组arraycatshapedogship
2条回答

这就是工作:

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')

相关问题 更多 >