简体   繁体   English

Python:如何在某些索引位置获取数组的值?

[英]Python: How to get values of an array at certain index positions?

I have a numpy array like this:我有一个像这样的 numpy 数组:

a = [0,88,26,3,48,85,65,16,97,83,91]

How can I get the values at certain index positions in ONE step?如何在一步中获取某些索引位置的值? For example:例如:

ind_pos = [1,5,7]

The result should be:结果应该是:

[88,85,16]

Just index using you ind_pos只需使用您的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])

The one liner "no imports" version单班轮“无进口”版本

a = [0,88,26,3,48,85,65,16,97,83,91]
ind_pos = [1,5,7]
[ a[i] for i in ind_pos ]

Although you ask about numpy arrays, you can get the same behavior for regular Python lists by using operator.itemgetter .尽管您询问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)

You can use index arrays , simply pass your ind_pos as an index argument as below:您可以使用索引数组,只需将您的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]

Index arrays do not necessarily have to be numpy arrays, they can be also be lists or any sequence-like object (though not tuples).索引数组不一定必须是 numpy 数组,它们也可以是列表或任何类似序列的对象(尽管不是元组)。

your code would be你的代码是

a = [0,88,26,3,48,85,65,16,97,83,91]

ind_pos = [a[1],a[5],a[7]]

print(ind_pos)

you get [88, 85, 16]你得到 [88, 85, 16]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM