Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带python列表的累积和_Python_List - Fatal编程技术网

带python列表的累积和

带python列表的累积和,python,list,Python,List,我必须使自己成为一个递归函数:累积求和(hist,initial_sum),我将用一个例子来解释我自己,它将更全面: hist=[0,1,2,3,4],initial=0 累计总和需要返回[0+0(第一个是初始总和),0+0+1,0+0+1+2,0+0+1+2+3,0+0+1+2+3+4]=[0,1,3,6,10] 第二个例子: 历史=[2,4,5,3],初始和=7 返回[2+7,2+7+4,2+7+4+5,2+7+4+5+3] 我无法更改累积和的参数,也无法更改列表历史 我试过了,但是我的程序

我必须使自己成为一个递归函数:
累积求和(hist,initial_sum)
,我将用一个例子来解释我自己,它将更全面:

hist=[0,1,2,3,4]
initial=0
累计总和
需要返回
[0+0(第一个是初始总和),0+0+1,0+0+1+2,0+0+1+2+3,0+0+1+2+3+4]
=
[0,1,3,6,10]

第二个例子: 历史=[2,4,5,3],初始和=7 返回[2+7,2+7+4,2+7+4+5,2+7+4+5+3]

我无法更改累积和的参数,也无法更改列表历史

我试过了,但是我的程序没有返回任何结果:

def cumulative_sum(hist, initial_sum=0):
    if len(hist)==0:
        new=[]
        return new.append(hist[0]+initial_sum)
    return cumulative_sum(hist[1:],new[-1])
第二个程序正在做这个工作,但我的老师告诉我不能使用全局变量(新)

新=[]

def cumulative_sum(hist, initial_sum=0):
    if len(hist) == 0:
        return new
    new.append(hist[0] + initial_sum)

    return cumulative_sum(hist[1:], new[-1])

如果你知道我在这里,谢谢你的帮助

您可以尝试
for
循环:

hist = [0, 1, 2, 3, 4]
cumulative_sum = []
c = 0
for i in hist:
    c += i
    cumulative_sum.append(c)
print(cumulative_sum)
或者尝试以下列表:

print([sum(hist[:i + 1])for i in range(len(hist))])
两个代码都输出:

[0, 1, 3, 6, 10]
编辑:

正如OP所提到的,他不想要一个
for
循环,因此请尝试以下功能:

def cumulative_sum(hist, initial_sum):
    if hist:
        return [hist[0] + initial_sum] + cumulative_sum(hist[1:], hist[0] + initial_sum)
    else:
        return []
    
print(cumulative_sum([2, 3, 5, 4], 7))
输出:

[9, 12, 17, 21]
def累计总和(历史,初始总和=0):
如果len(hist):#长度非零
总计=初始值+历史值[0]#计算第一个值
返回[total]+累计_和(hist[1:],total)#追加剩余值的结果
否则:#长度为零
返回[]
打印(累计总和([0,1,2,3]))
打印(累计金额([2,3,5,4],7))
[0,1,3,6]
[9, 12, 17, 21]

我不能在和同时使用。。。但是thanks@DoronSachaSlomovits请检查我的第二个例子,我使用一个列表comprehension@DoronSachaSlomovits如果我的代码对您有帮助,请接受:-)@DoronSachaSlomovits请检查我编辑的部分,现在应该可以用了抱歉,但是我们不能使用for或,因为我想他们得到了一个程序,检查是否有for或while…如果你可以使用itertools使用:
list(itertools.acculate(data))
@SreeramTP他想要一个
初始值
东西too@U11-Forward
itertools.acculate
有一个
initial
关键字,尽管它的工作原理稍有不同。它以值开头,结果是多出一个元素
itertools.accumulate(hist[1:],initial=hist[0])
可以。好的,谢谢,我会检查的,我不知道