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

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

我如何计算它们的总和:

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

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

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

当前回答

解决这个问题最简单的方法是:

l =[1,2,3,4,5]
sum=0
for element in l:
    sum+=element
print sum

其他回答

本着itertools的精神。灵感来自双人食谱。

from itertools import tee, izip

def average(iterable):
    "s -> (s0,s1)/2.0, (s1,s2)/2.0, ..."
    a, b = tee(iterable)
    next(b, None)
    return ((x+y)/2.0 for x, y in izip(a, b))

例子:

>>>list(average([1,2,3,4,5]))
[1.5, 2.5, 3.5, 4.5]
>>>list(average([1,20,31,45,56,0,0]))
[10.5, 25.5, 38.0, 50.5, 28.0, 0.0]
>>>list(average(average([1,2,3,4,5])))
[2.0, 3.0, 4.0]

保持简单:

def cool_sum(list: numbers):
    b = 0;
    for i in numbers:
        b += i
    return b;


a = [1, 2, 4]
print(cool_sum(a))

我只使用带有map()的

a = [1,2,3,4,5,6,7,8,9,10]
b = map(lambda x, y: (x+y)/2.0, fib[:-1], fib[1:])
print b
import numpy as np    
x = [1,2,3,4,5]
[(np.mean((x[i],x[i+1]))) for i in range(len(x)-1)]
# [1.5, 2.5, 3.5, 4.5]

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

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