我正在寻找一种更快,更pythonic的方式来创建一个列表,该列表的元素取决于另一个列表中的多个索引。代码示例:

import numpy as np
xrandomsorted = np.sort(np.random.randn(1000000)) #input which needs to be used
Npts = int(len(xrandomsorted)/3)

#Part to be optimised begins here
final_list = np.zeros(Npts)

for i in range(Npts):
    xval = 12 - 3*xrandomsorted[i] + 7*xrandomsorted[2*i] - xrandomsorted[3*i]
    final_list[i] = xval


我发现此解决方案的速度略快(尽管我仍然认为可能会有更好的解决方案!):

list1 = xrandomsorted[0:Npts]
list2 = xrandomsorted[::2][0:Npts]
list3 = xrandomsorted[::3][0:Npts]

final_list = []

for value1, value2, value3 in zip(list1, list2, list3):
    xval = 12 - 3*value1 + 7*value2 -value3
    final_list.append(xval)


还有其他方法可以在不使用numba / cython的情况下使代码更快吗?

最佳答案

您可以将NumPy切片用于矢量化解决方案:

n = Npts
A = xrandomsorted
res = 12 - 3*A[:n] + 7*A[:n*2:2] - A[:n*3:3]


该语法类似于Python list切片语法,即arr[start : stop : step]

09-26 09:38