给定一个数字列表,例如:
[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, ...]
当前回答
本着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]
其他回答
你可以试试这种方法:
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
使用简单的列表-理解和求和:
>> sum(i for i in range(x))/2. #if x = 10 the result will be 22.5
你也可以使用递归来做同样的事情:
Python代码片段:
def sumOfArray(arr, startIndex):
size = len(arr)
if size == startIndex: # To Check empty list
return 0
elif startIndex == (size - 1): # To Check Last Value
return arr[startIndex]
else:
return arr[startIndex] + sumOfArray(arr, startIndex + 1)
print(sumOfArray([1,2,3,4,5], 0))
我使用一个while循环来得到结果:
i = 0
while i < len(a)-1:
result = (a[i]+a[i+1])/2
print result
i +=1
一种简单的方法是使用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。您可以通过使用集合来减少这种情况。