这是所有高级Python真正聪明的用户所面临的问题。我的输入是Python numpy数组中的一系列数字。它们是按线性顺序排列的浮点值。我需要创建一个新的几何序列,其中:
新的第一个值=原始的第一个值
新的第二个值=原始值两个和三个的总和
新的第三个值=原始值的四至七个之和
新的第四个值=八到十五的值之和
我当然可以通过遍历数据来做到这一点,但我需要尽快完成这一处理-数组很大。什么是最快的方法?
示例:
12.0, 3.4, 9.2, 7.7, 4.9, 3.8, 6.9
应成为:
12.0, 12.6, 23.3
您可以使用np.add.reduceat
和int.bit_length
。
示例:
# make example sequence
a = np.arange(100.0)
# form sums
np.add.reduceat(a,(1<<np.arange(a.size.bit_length()))-1)
# array([ 0., 3., 18., 84., 360., 1488., 2997.])
这将添加项目0; 1 + 2; 3 + 4 + 5 + 6;您的示例建议的是您真正想要的东西。
from math import log, floor
a = [12.0, 3.4, 9.2, 7.7, 4.9, 3.8, 6.9]
print([sum(a[2**i-1:2**(i+1)-1]) for i in range(floor(log(len(a), 2)) + 1)])
此输出:
[12.0, 12.6, 23.3]
用于总和的索引是:
[(0, 1), (1, 3), (3, 7), (7, 15), (15, 31), ...]
当列表的长度不等于2的幂时,可以缩短最后的总和。
seq = [12.0, 3.4, 9.2, 7.7, 4.9, 3.8, 6.9]
r = 0 # this is the binary power (2^r)
g_seq = [] # list to contain your final answer
i = 0 # index of start position for summing at each iteration
while i < len(seq): # once i reaches the last element, stop looping
n = 2**r # number of elements to sum in each iteration
j = i + n # index of end position for summing
r+= 1 # increment power for next iteration
subseq = seq[i:j] # slice of your input sequence to be summed
g_seq.append(sum(subseq)) # sum the slice and append to answer list
i = j # j becomes the i for the next iteration
print(g_seq)
--------------------
[12.0, 12.6, 23.300000000000004]
编辑:添加评论