我有一系列的值,例如:
values = ['A', 'B', 'C', 'D', 'E']
以及数据类型为int64:的numpy数组中的索引的长列表
indexes = np.array([3, 0, 1], dtype=np.int64)
我想打印这个数组上索引指示的第一个列表中的项目,但如果我这样做:
print(values[indexes])
然后失败:
TypeError: only integer scalar arrays can be converted to a scalar index
我想看看:
print(values[indexes])
>>> ['D', 'B', 'A']
我该怎么做?
您不能直接尝试访问这样的值,但根据indexes
列表,您可以使用列表理解(或for循环(来访问values
列表中的每个单独项目。
import numpy as np
values = ['A', 'B', 'C', 'D', 'E']
indexes = np.array([3, 0, 1], dtype=np.int64)
print([values[i] for i in indexes])
另一种方法是制作这样的函数:
import numpy as np
def getValues(values, indexes):
return [values[i] for i in indexes]
values = ['A', 'B', 'C', 'D', 'E']
indexes = np.array([3, 0, 1], dtype=np.int64)
print(getValues(values, indexes))