给定一个数字列表,例如:
[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, ...]
当前回答
你也可以使用递归来做同样的事情:
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))
其他回答
问题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)
使用简单的列表-理解和求和:
>> sum(i for i in range(x))/2. #if x = 10 the result will be 22.5
一种简单的方法是使用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。您可以通过使用集合来减少这种情况。
简短而简单:
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]
对一串数字求和:
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:]))