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

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

我如何计算它们的总和:

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

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

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

当前回答

对一串数字求和:

sum(list_of_nums)

使用列表推导式生成一个新列表,其中相邻元素在xs中求平均值:

[(x + y) / 2 for x, y in zip(xs, xs[1:])]

将所有相邻元素求和为一个值:

sum((x + y) / 2 for x, y in zip(xs, xs[1:]))

其他回答

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

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

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

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]

简短而简单:

def ave(x,y):
  return (x + y) / 2.0

map(ave, a[:-1], a[1:])

这是它的样子:

>>> a = range(10)
>>> map(ave, a[:-1], a[1:])
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]

由于Python在处理两个列表上的映射时有些愚蠢,你必须截断列表a[:-1]。如果你使用itertools.imap,它会像你期望的那样工作:

>>> import itertools
>>> itertools.imap(ave, a, a[1:])
<itertools.imap object at 0x1005c3990>
>>> list(_)
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]
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]

保持简单:

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


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