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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25201438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:52:45  来源:igfitidea点击:

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

pythonarraysnumpyindexing

提问by MoTSCHIGGE

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]

采纳答案by Padraic Cunningham

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

回答by Ffisegydd

You can use index arrays, simply pass your ind_posas 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 数组,它们也可以是列表或任何类似序列的对象(尽管不是元组)。

回答by user3906621

your code would be

你的代码是

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

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

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

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

print ind_pos

print ind_pos

you get [88, 85, 16]

你得到 [88, 85, 16]

回答by chepner

Although you ask about numpyarrays, you can get the same behavior for regular Python lists by using operator.itemgetter.

尽管您询问numpy数组,但您可以通过使用operator.itemgetter.

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

回答by Ohad Cohen

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 ]