如何编写代码将索引之间的所有数字相加?阵列numbers
和indices
是相关的。前两个指标值是0-3
,所以指数0-3之间的numbers
加起来是1 + 5 + 6 = 12
。期望值就是我要找的。我试图在不使用for循环的情况下获得结果。
numbers = np.array([1, 5, 6, 7, 4, 3, 6, 7, 11, 3, 4, 6, 2, 20]
indices = np.array([0, 3 , 7, 11])
预期输出:
[12, 41, 22]
我不确定你是如何得到预期的输出-从我的计算,指标之间的总和应该是[12, 20, 25]
。下面的代码计算:
numbers = np.array([1, 5, 6, 7, 4, 3, 6, 7, 11, 3, 4, 6, 2, 20])
indexes = np.array([0, 3, 7, 11])
tmp = np.zeros(len(numbers) + 1)
np.cumsum(numbers, out=tmp[1:])
result = np.diff(tmp[indexes])
输出为[12, 20, 25]
这是如何工作的?它创建一个只比numbers数组大一个大小的数组(为了使第一个元素为零)。然后计算元素的累积和,从tmp
数组的索引1开始。然后,它在提供的索引处取tmp
数组的差值。例如,取数组从索引3 (value = 12)到索引7 (value = 32)的累加和的差,32-12 = 20。
您可能正在寻找np.add.reduceat
:
>>> np.add.reduceat(numbers, indices)
array([12, 20, 25, 28], dtype=int32)