我试图加快一段代码,称为LOT,以期缩短脚本运行时间。
说我有一个多维数组:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
一维指数数组:
[2], [0], [1]
没有循环,有没有办法从多维数组中检索这些索引,即:
[3], [4], [8]
任何帮助表示赞赏!
答案 0 :(得分:3)
您可以使用itertools.starmap
import itertools
def get_values_from_indices(array_values, array_indices):
"""
This function will accept two params,
once is a multi-dimensional list, and other one is list of indices.
"""
return list(itertools.starmap(lambda x, y: x[y[0]], zip(array_values, array_indices)))
<强>样本强>
multi_dimensional_array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list_of_indices = [[2], [0], [1]]
result = get_values_from_indices(multi_dimensional_array , list_of_indices)
print(result)
# [3, 4, 8]
答案 1 :(得分:0)
不确定你想要的结果如何,但是你可以通过numpy获得类似的结果。
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# array([[1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]])
a[[0,1,2],[2,0,1]] # array([3, 4, 8])
a[[0,1,2],[1,2,1]] # array([2, 6, 8])
甚至可能是,
indices = [[2],[0],[1]]
a[range(len(indices)), np.reshape(indices, -1)] # array([3, 4, 8])
答案 2 :(得分:0)
列表理解:
listOfList = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
indexInto = [2, 0, 1] # first version works for this
indexTwo = [[2], [0], [1]] # second version works for this
# first version
values = [listOfList[lili][indexInto[lili]] for lili in range(len(listOfList))] # both lists need same length
# second version
values2 = [listOfList[lili][indexTwo[lili][0]] for lili in range(len(listOfList))] # both lists need same length
print( values)
print( values2)
输出:
[3, 4, 8]
[3, 4, 8]
答案 3 :(得分:0)
Numpy解决方案:
import numpy as np
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
ind = [[2], [0], [1]]
a = np.array(L)
b = np.array(ind)
c = a[np.arange(len(a)), b.reshape(-1)]
print (c.tolist())
[3, 4, 8]
答案 4 :(得分:0)
另一个愚蠢的解决方案:
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
a2 = [[2], [0], [1]]
a[np.arange(len(a)), np.concatenate(a2)] # array([3, 4, 8])
答案 5 :(得分:0)
带有地图的Lambda解决方案,无需在一行中导入任何外部模块:
list_1=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
indices=[[2], [0], [1]]
print(list(map(lambda x,y :list(map(lambda z:x[z],y)),list_1,indices)))
输出:
[[3], [4], [8]]