给定一个数字列表,例如:
[1, 2, 3, 4, 5, ...]
我如何计算它们的总和:
1 + 2 + 3 + 4 + 5 + ...
我如何计算他们的两两平均值:
[(1+2)/2, (2+3)/2, (3+4)/2, (4+5)/2, ...]
给定一个数字列表,例如:
[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
其他回答
简短而简单:
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]
问题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 = [1,2,3,4]
sum(a)
sum(a)返回10
遍历列表中的元素并像这样更新总数:
def sum(a):
total = 0
index = 0
while index < len(a):
total = total + a[index]
index = index + 1
return total
这么多解决方案,但我最喜欢的还是没有:
>>> import numpy as np
>>> arr = np.array([1,2,3,4,5])
numpy数组与列表没有太大区别(在这个用例中),除了你可以像对待数字一样对待数组:
>>> ( arr[:-1] + arr[1:] ) / 2.0
[ 1.5 2.5 3.5 4.5]
完成了!
解释
花式索引的意思是:[1:]包括从1到最后的所有元素(因此省略了元素0),而[:-1]是除了最后一个以外的所有元素:
>>> arr[:-1]
array([1, 2, 3, 4])
>>> arr[1:]
array([2, 3, 4, 5])
将这两个元素相加,就得到了一个包含元素(1+2)(2+3)等的数组。 请注意,我是除以2.0,而不是2,因为否则Python认为您只使用整数并产生四舍五入的整数结果。
使用numpy的优点
Numpy比围绕数字列表的循环要快得多。这取决于你的列表有多大,快几个数量级。此外,它的代码更少,至少对我来说,它更容易阅读。 我正在努力养成对所有数字组都使用numpy的习惯,这对于我本来必须编写的所有循环和循环中的循环是一个巨大的改进。