我有一个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']]
是否有任何pythonic方式或快捷方式来实现输出而不迭代每个索引值?
答案 0 :(得分:2)
如果您将列表设为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')
答案 1 :(得分:0)
这就是工作:
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]