如何在列表中找到数字的累积和?time_interval = [4, 6, 12]我想总结一下这些数字[4, 4+6, 4+6+12]为了得到名单t = [4, 10, 22].我尝试了以下几点:for i in time_interval:
t1 = time_interval[0]
t2 = time_interval[1] + t1
t3 = time_interval[2] + t2 print(t1, t2, t3)4 10 224 10 224 10 22
3 回答
婷婷同学_
TA贡献1844条经验 获得超8个赞
numpy
cumsum
:
import numpy as np a = [4,6,12]np.cumsum(a)#array([4, 10, 22])
accumu
:
In [136]: timeit list(accumu(range(1000)))10000 loops, best of 3: 161 us per loopIn [137]: timeit list(accumu(xrange(1000)))10000 loops, best of 3: 147 us per loopIn [138]: timeit np.cumsum(np.arange(1000))100000 loops, best of 3: 10.1 us per loop
开心每一天1111
TA贡献1836条经验 获得超13个赞
a = [4, 6, 12]reduce(lambda c, x: c + [c[-1] + x], a, [0])[1:]
[4, 10, 22]
添加回答
举报
0/150
提交
取消