![](/img/trans.png)
[英]How to add the current item with the previous item in a list using python
[英]How to add each item in a list to the previous one in Python?
我有一个列表,我想将列表中的每个元素添加到上一个元素。 例如,如果我有列表(1,1,3,3,4)
,我希望程序输出(1,2,5,8,12)
。
[sum(a[:i]) for i in range(1,len(a)+1)]
这可能是最简单的方法...我想...
numpy.cumsum(a)
我认为也可以
>>> import itertools
>>> list(itertools.accumulate([1,1,3,3,4], lambda total,el: total+el))
[1, 2, 5, 8, 12]
免责声明 :在python 3.2中添加
for i in range(1, len(arr)):
arr[i] += arr[i - 1]
比Joran Beasley Loop更有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.