假设我有以下两个numpy数组。 idxes
包含我想从arr
返回的元素的索引。
arr = ['a', 'b', 'c' ]
idxes = [1, 2]
// This is the result I'm after
result = ['b', 'c']
最初的想法是使用np.where
和一个布尔数组,但是使用起来似乎很尴尬,并且想知道是否有一个更优雅的解决方案,因为我对numpy很陌生。
答案 0 :(得分:2)
使用这种简单的列表理解方法,它遍历idxes
并在idxes
中的i
(arr
)中得到索引的值:
print([arr[i] for i in idxes])
输出:
['b', 'c']
如果它们是numpy数组:
print(arr[idxes])
输出:
['b' 'c']
答案 1 :(得分:0)
另一种方式:
list(map(arr.__getitem__, idxes))
输出:
['b', 'c']