如何在Python中列出列表中的所有数字?

时间:2015-03-01 13:13:30

标签: 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)

问题是我正在使用"返回元素"但不是" math.fsum(元素) 我做错了什么?

1 个答案:

答案 0 :(得分:1)

我已经解决了一些问题,并提出了一些建议:

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.