如何在Python中对列表中的所有数字求和?
由以下代码组成:如何在Python中对列表中的所有数字求和?,python,list,sum,Python,List,Sum,由以下代码组成: import math def z(a,b,s): import math elements = list() for i in range(a,b): elements.append(i**-s) return elements f = math.fsum(elements) print (f) 问题是,我得到的是带有“returnelements”的列表,而不是“math.fsum(eleme
import math
def z(a,b,s):
import math
elements = list()
for i in range(a,b):
elements.append(i**-s)
return elements
f = math.fsum(elements)
print (f)
问题是,我得到的是带有“returnelements”的列表,而不是“math.fsum(elements)
我做错了什么?我已经解决了一些问题,并提出了一些建议:
import math # You should be aware that python has a builtin sum function
def z(a,b,s):
#import math << There is no need to import the module twice, so I've commented it, meaning it won't execute
elements = list() # Unconventional, but it works - it's more common to just create a literal empty list like so: elements = []
for i in range(a,b):
elements.append(i**-s)
f = math.fsum(elements)
return elements, f # Here we're returning both your list AND the sum in a "tuple" (assuming you want to return both)
# Note that once the return function executes, the interpreter exits the function, and nothing else in the function will be executed.
elements, f = z(5, 10, 3) # Here we're calling the function, and "unpacking" the two things we returned from the tuple into two variables.
print f # This will print out your sum.
import math#您应该知道python有一个内置的求和函数
定义z(a、b、s):
#导入数学您可能希望从基本Python教程开始。return
语句立即返回值,其余语句将被忽略。为什么要这样做?您return
ed很早就从函数中删除了;函数结束于此。FWIW,使用可能比使用内置的sum()更可取
,当您需要精度时。(但如果我想计算与zeta系列相关的内容,我可能会使用mpmath…)我会使用列表理解:元素=[I**-s代表范围(a,b)中的I]
@PM2Ring yep,同意-只是想确保他知道sum
。Brionius:公平点。@Matthias:list comp很酷,很简洁,我一直在使用它们,但它们不一定比基于循环的代码的等效简单快,即使list comp可以让你避免.append()
call in the loop.PM 2Ring@您能告诉我更多的原因吗?事实上,我正在Rieman Zeta函数上尝试一些公式。谢谢