我有一个如下所示的数组:
testdata = [-2, -1, 0, 1, 2, 3, 10, 3, 2, 1, 0, -1, -2]
所以它有一个最大值,在左边和右边,值逐渐下降到零,然后它的值可以低于0
我的代码的目的是找到数组的最大值,并将所有这些值向左和向右相加,直到值为0(包括最大值)
为了测试我的代码,我生成了这样一个较大的数组(忽略可能小于0的值):
data1 = [x for x in range(0, 100000, 1)]
data2 = [x for x in range(100000, -1, -1)]
data3 = data1 + data2
我能想出的最快代码如下所示:
j = 1
k = 0
max_index = np.where(data3 == np.amax(data3))[0][0]
while data3[max_index + j] > 0:
j += 1
while data3[max_index - k] > 0:
k += 1
summ1 = np.sum(data3[max_index:(max_index+j)])
summ2 = np.sum(data3[(max_index-k):max_index])
total = summ1 + summ2
print(total)
关于如何更快地提高这一点,有什么建议吗
您可以使用掩蔽而不是使用循环
遮罩
[data3[max_index:] > 0]
和[data3[:max_index] > 0]
等同于滑动[max_index:(max_index+j)]
和[(max_index-k):max_index]
,除非您不必费心自己寻找j
和k
这在很大程度上取决于数据。似乎您正在试图找到一种有效的方法来返回数组中某个内容的第一个索引。嗯,there isn't an efficient one in ^{} 因为在} 是为了优于
numpy
中只允许整个数组的迭代,而you can use ^{numpy
如果您需要对列表中的一大部分或一小部分求和,
numpy
是一个不错的选择:否则,使用pythonic
index
方法(或numba
):基准。 我得到的第一种方法是在Jupyter笔记本中使用
%timeit
decorator,速度快20倍:相关问题 更多 >
编程相关推荐