给定一个数字列表,例如:

[1, 2, 3, 4, 5, ...]

我如何计算它们的总和:

1 + 2 + 3 + 4 + 5 + ...

我如何计算他们的两两平均值:

[(1+2)/2, (2+3)/2, (3+4)/2, (4+5)/2, ...]

当前回答

试试以下方法:

mylist = [1, 2, 3, 4]   

def add(mylist):
    total = 0
    for i in mylist:
        total += i
    return total

result = add(mylist)
print("sum = ", result)

其他回答

试试以下方法:

mylist = [1, 2, 3, 4]   

def add(mylist):
    total = 0
    for i in mylist:
        total += i
    return total

result = add(mylist)
print("sum = ", result)

生成器是一种简单的编写方法:

from __future__ import division
# ^- so that 3/2 is 1.5 not 1

def averages( lst ):
    it = iter(lst) # Get a iterator over the list
    first = next(it)
    for item in it:
        yield (first+item)/2
        first = item

print list(averages(range(1,11)))
# [1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]

你可以试试这种方法:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sm = sum(a[0:len(a)]) # Sum of 'a' from 0 index to 9 index. sum(a) == sum(a[0:len(a)]
print(sm) # Python 3
print sm  # Python 2

尝试使用列表理解。喜欢的东西:

new_list = [(old_list[i] + old_list[i+1])/2 for i in range(len(old_list-1))]

使用简单的列表-理解和求和:

>> sum(i for i in range(x))/2. #if x = 10 the result will be 22.5