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

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

我如何计算它们的总和:

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

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

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

当前回答

遍历列表中的元素并像这样更新总数:

def sum(a):
    total = 0
    index = 0
    while index < len(a):
        total = total + a[index]
        index = index + 1
    return total

其他回答

我使用一个while循环来得到结果:

i = 0
while i < len(a)-1:
   result = (a[i]+a[i+1])/2
   print result
   i +=1

我只使用带有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

所有的回答都显示了一种纲领性和一般性的方法。我建议用一种数学方法来解决你的问题。它可以更快,特别是对于长列表。它之所以有效,是因为你的列表是一个到n的自然数列表:

假设我们有自然数1,2,3,…10:

>>> nat_seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

你可以在列表中使用求和函数:

>>> print sum(nat_seq)
55

你也可以使用公式n*(n+1)/2,其中n是列表中最后一个元素的值(这里:nat_seq[-1]),这样你就可以避免遍历元素:

>>> print (nat_seq[-1]*(nat_seq[-1]+1))/2
55

生成序列(1+2)/2,(2+3)/2,…,(9+10)/2你可以使用生成器和公式(2*k-1)/2。(注意点使值为浮点)。在生成新列表时,必须跳过第一个元素:

>>> new_seq = [(2*k-1)/2. for k in nat_seq[1:]]
>>> print new_seq
[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]

在这里,你也可以使用列表中的sum函数:

>>> print sum(new_seq)
49.5

但是你也可以使用公式(((n*2+1)/2)**2-1)/2,这样你就可以避免遍历元素:

>>> print (((new_seq[-1]*2+1)/2)**2-1)/2
49.5

问题2: 对一组整数求和:

a = [2, 3, 5, 8]
sum(a)
# 18
# or you can do:
sum(i for i in a)
# 18

如果列表中包含整数作为字符串:

a = ['5', '6']
# import Decimal: from decimal import Decimal
sum(Decimal(i) for i in a)
>>> a = range(10)
>>> sum(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del sum
>>> sum(a)
45

sum似乎已经在代码的某个地方定义了,并且覆盖了默认函数。所以我删除了它,问题解决了。