Python - 如何根据索引数组从数组中提取元素?
Python - How to extract elements from an array based on an array of indices?
假设我有一个元素列表 X
和一个索引 Y
。
X = [1, 2, 3, 4, 5, 6, 7]
Y = [0, 3, 4]
Python 中是否有函数可以根据 Y
中提供的索引从 X
中提取元素?执行后,X
将是:
X = [1, 4, 5]
X = [X[index] for index in Y]
这是一个列表理解;您可以查看该主题以了解更多信息。
@Prune 提供的列表理解是纯粹的方式 python。如果您不介意 numpy
,使用他们的索引方案可能更容易:
import numpy as np
>>> np.array(X)[Y]
array([1, 4, 5])
您可以将 list.__getitem__
与 map
一起使用:
X = [1, 2, 3, 4, 5, 6, 7]
Y = [0, 3, 4]
res = list(map(X.__getitem__, Y)) # [1, 4, 5]
或者,如果您喜欢使用第 3 方库,则可以使用 NumPy:
import numpy as np
X = np.array([1, 2, 3, 4, 5, 6, 7])
res = X[Y] # array([1, 4, 5])
假设我有一个元素列表 X
和一个索引 Y
。
X = [1, 2, 3, 4, 5, 6, 7]
Y = [0, 3, 4]
Python 中是否有函数可以根据 Y
中提供的索引从 X
中提取元素?执行后,X
将是:
X = [1, 4, 5]
X = [X[index] for index in Y]
这是一个列表理解;您可以查看该主题以了解更多信息。
@Prune 提供的列表理解是纯粹的方式 python。如果您不介意 numpy
,使用他们的索引方案可能更容易:
import numpy as np
>>> np.array(X)[Y]
array([1, 4, 5])
您可以将 list.__getitem__
与 map
一起使用:
X = [1, 2, 3, 4, 5, 6, 7]
Y = [0, 3, 4]
res = list(map(X.__getitem__, Y)) # [1, 4, 5]
或者,如果您喜欢使用第 3 方库,则可以使用 NumPy:
import numpy as np
X = np.array([1, 2, 3, 4, 5, 6, 7])
res = X[Y] # array([1, 4, 5])