如何在Python中求和

Fay*_*l F 6 python sum function

我想知道如何在 python 中表示总和而不需要像这里这样的循环

我们有:

def rosen(x):
    """The Rosenbrock function"""
    return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)
Run Code Online (Sandbox Code Playgroud)

我的功能如下:V(theta) = Sum(i=1->N)[a0*(cos(i*theta)]

预先感谢您的帮助 :):)

Ash*_*ary 3

就像是:

def V(theta,N):
    return sum(a0*(cos(i*theta) for i in range(1,N+1))
print V(theta,N) 
Run Code Online (Sandbox Code Playgroud)

或者你可以使用lambda

V =lambda theta,N : sum(a0*(cos(i*theta) for i in range(1,N+1))   
print V(theta,N) 
Run Code Online (Sandbox Code Playgroud)