取一个没有sum的列表的总和()

时间:2015-10-12 04:53:12

标签: python

我有一个列表,当用户输入他们想要的随机数时会生成该列表。我想使用sum()将总和加在一起。我怎么能这样做?

xAmount = int(input("How man numbers would you like to input: "))

numList = []

for i in range(0, xAmount):
     numList.append(int(input("Enter a number: ")))



print(numList)

从这里

3 个答案:

答案 0 :(得分:3)

根本不需要列表。

xAmount = int(input("How man numbers would you like to input: "))
result = 0

for i in range(0, xAmount):
     result = result + int(input("Enter a number: "))

print(result)

答案 1 :(得分:3)

将总和存储在临时变量中。继续将输入数字添加到临时变量:

xAmount = int(input("How man numbers would you like to input: "))

numList = []
numList_sum = 0

for i in range(0, xAmount):
     inputted_number = int(input("Enter a number: "))
     numList_sum += inputted_number
     numList.append(inputted_number)



print(numList)
print(numList_sum)

答案 2 :(得分:0)

要对列表求和,只需遍历列表,将各个值相加:

num_total = 0
for value in numList:
    num_total += value

您也可以使用reduce,但这可能不符合您的h / w要求:

from functools import reduce
from operator import add
num_total = reduce(add, numList, 0)