joh*_*n_R 2 python list python-3.x
我有一个旧列表,我想将每个元素总结为一个新列表:
lst_old = [1, 2, 3, 4, 5]
lst_new = [1, 3, 6, 10, 15]
Run Code Online (Sandbox Code Playgroud)
有没有一种优雅的方法在Python 3中使用短代码和快速代码实现它?除了sum()打印最后一个元素,我无法找到适合我的问题的解决方案.
你可以使用itertools.accumulate,例如:
from itertools import accumulate
lst_old = [1, 2, 3, 4, 5]
lst_new = list(accumulate(lst_old))
# [1, 3, 6, 10, 15]
Run Code Online (Sandbox Code Playgroud)