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

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

我如何计算它们的总和:

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

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

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

当前回答

问题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)

其他回答

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

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]

尝试使用列表理解。喜欢的东西:

new_list = [(old_list[i] + old_list[i+1])/2 for i in range(len(old_list-1))]
n = int(input("Enter the length of array: "))
list1 = []
for i in range(n):
    list1.append(int(input("Enter numbers: ")))
print("User inputs are", list1)

list2 = []
for j in range(0, n-1):
    list2.append((list1[j]+list1[j+1])/2)
print("result = ", list2)

你也可以使用递归来做同样的事情:

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