我想定义一个函数,在其中输入多个数字,该函数将把前两个数字加起来,然后将答案添加到第三个数字,然后将答案添加到第四个数字,依此类推,直到所有数字都已递增起来 例如:
def function(x1, x2, x3, x4):
ind_1 = x1 + x2
ind_2 = ind_1 + x3
ind_3 = ind_2 + x4
return x1, ind_1, ind_2, ind_3
function(175, 107, 107, 95)
OUT: (175, 282, 389, 484)
我如何扩大规模,以便在通用数字列表上重复执行此操作,而每次使用时都会更改该数字,而无需手动写出函数中的所有总和?
谢谢!
我将使用* args处理多个参数。它允许您传递任意数量的参数。
accumulate
does exactly what you want, see other examples in the documentation. You do not have to make alist
from the returned generator if you only want to iterate over it.