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

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

我如何计算它们的总和:

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

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

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

当前回答

一种简单的方法是使用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。您可以通过使用集合来减少这种情况。

其他回答

试试以下方法:

mylist = [1, 2, 3, 4]   

def add(mylist):
    total = 0
    for i in mylist:
        total += i
    return total

result = add(mylist)
print("sum = ", result)
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)

让我们让初学者容易:-

global关键字将允许在主函数中分配全局变量消息,而不产生新的局部变量

message = "这是一个全局变量!" def main (): 全球信息 message = "This is a local" 打印(消息) main () #输出“这是一个本地”-从函数调用 打印(消息) #输出“This is a local”——从外部作用域

这个概念叫做影子

在Python中对数字列表求和

Nums = [1,2,3,4,5] Var = 0 def金额(): 对于nums中的num: 全局变量 Var = Var + num 打印(var) 如果__name__ == '__main__': 金额()

输出= 15

你可以试试这种方法:

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

这个问题在这里得到了解答

a = [1,2,3,4]
sum(a) 

sum(a)返回10