我有一个像这样的numpy数组:
a = [0,88,26,3,48,85,65,16,97,83,91]
如何在一步中获取某些指数位置的值?例如:
ind_pos = [1,5,7]
结果应为:
[88,85,16]
答案 0 :(得分:14)
使用ind_pos
ind_pos = [1,5,7]
print (a[ind_pos])
[88 85 16]
In [55]: a = [0,88,26,3,48,85,65,16,97,83,91]
In [56]: import numpy as np
In [57]: arr = np.array(a)
In [58]: ind_pos = [1,5,7]
In [59]: arr[ind_pos]
Out[59]: array([88, 85, 16])
答案 1 :(得分:9)
一个班轮"没有进口"版本
a = [0,88,26,3,48,85,65,16,97,83,91]
ind_pos = [1,5,7]
[ a[i] for i in ind_pos ]
答案 2 :(得分:4)
虽然您询问numpy
数组,但使用operator.itemgetter
可以获得常规Python列表的相同行为。
>>> from operator import itemgetter
>>> a = [0,88,26,3,48,85,65,16,97,83,91]
>>> ind_pos = [1, 5, 7]
>>> print itemgetter(*ind_pos)(a)
(88, 85, 16)
答案 3 :(得分:2)
您可以使用index arrays,只需将ind_pos
作为索引参数传递,如下所示:
a = np.array([0,88,26,3,48,85,65,16,97,83,91])
ind_pos = np.array([1,5,7])
print(a[ind_pos])
# [88,85,16]
索引数组不一定必须是numpy数组,它们也可以是列表或任何类似序列的对象(尽管不是元组)。
答案 4 :(得分:-3)
您的代码将是
a = [0,88,26,3,48,85,65,16,97,83,91]
ind_pos = ind_pos = [a[1],a[5],a[7]]
print ind_pos
你得到[88,85,16]