给定一个数字列表,例如:
[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, ...]
当前回答
你可以试试这种方法:
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
其他回答
所有的回答都显示了一种纲领性和一般性的方法。我建议用一种数学方法来解决你的问题。它可以更快,特别是对于长列表。它之所以有效,是因为你的列表是一个到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)
解决这个问题最简单的方法是:
l =[1,2,3,4,5]
sum=0
for element in l:
sum+=element
print sum
使用成对的itertools食谱:
import itertools
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return itertools.izip(a, b)
def pair_averages(seq):
return ( (a+b)/2 for a, b in pairwise(seq) )
一种简单的方法是使用iter_tools排列
# If you are given a list
numList = [1,2,3,4,5,6,7]
# and you are asked to find the number of three sums that add to a particular number
target = 10
# How you could come up with the answer?
from itertools import permutations
good_permutations = []
for p in permutations(numList, 3):
if sum(p) == target:
good_permutations.append(p)
print(good_permutations)
结果是:
[(1, 2, 7), (1, 3, 6), (1, 4, 5), (1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 1, 7), (2, 3,
5), (2, 5, 3), (2, 7, 1), (3, 1, 6), (3, 2, 5), (3, 5, 2), (3, 6, 1), (4, 1, 5), (4,
5, 1), (5, 1, 4), (5, 2, 3), (5, 3, 2), (5, 4, 1), (6, 1, 3), (6, 3, 1), (7, 1, 2),
(7, 2, 1)]
注意,顺序很重要——即1,2,7也表示为2,1,7和7,1,2。您可以通过使用集合来减少这种情况。