my_list = [0, 219, 211, 212, 212]
我需要以这种方式对项目求和:
项目+项目,(项目+项目)+项目,(项目+项目+项目)+项目...
0+219, (219)+211, (430)+212, (641)+212
为了更清楚,这是我需要得到的总和:
new_list = [219, 430, 641, 853]
我认为解决方案可能是列表推导式,而像这样的东西只会返回每个项目与下一个项目的总和。
[(x + y) for (x, y) in zip(my_list[:-1], my_list[1:])]
有什么想法吗?
请您参考如下方法:
您可以复制 itertools.accumulate() documentation description来自 Python 3:
import operator
def accumulate(iterable, func=operator.add):
'Return running totals'
# accumulate([1,2,3,4,5]) --> 1 3 6 10 15
# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
it = iter(iterable)
try:
total = next(it)
except StopIteration:
return
yield total
for element in it:
total = func(total, element)
yield total
这将对输入列表中的值求和,产生一个运行总和:
>>> my_list = [0, 219, 211, 212, 212]
>>> list(accumulate(my_list))
[0, 219, 430, 642, 854]
您可以根据您的具体情况定制模式,删除 func 自定义点并忽略第一个总数:
def accumulate(iterable):
it = iter(iterable)
try:
total = next(it)
except StopIteration:
return
for element in it:
total += element
yield total
现在它为 4 个输入生成 3 个值:
>>> list(accumulate(my_list))
[219, 430, 642, 854]
