簡體   English   中英

Python:如何在某些索引位置獲取數組的值?

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

我有一個像這樣的 numpy 數組:

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

如何在一步中獲取某些索引位置的值? 例如:

ind_pos = [1,5,7]

結果應該是:

[88,85,16]

只需使用您的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])

單班輪“無進口”版本

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

盡管您詢問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)

您可以使用索引數組,只需將您的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 數組,它們也可以是列表或任何類似序列的對象(盡管不是元組)。

你的代碼是

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

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

print(ind_pos)

你得到 [88, 85, 16]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM