Python:带有for循环的数字列表的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23309657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Total sum of a list of numbers with the for loop
提问by nubz0r
I'm new to Python and I have this problem:
我是 Python 新手,遇到了这个问题:
I need to program a Python function that gives me back the sum of a list of numbers using a for loop.
我需要编写一个 Python 函数,该函数使用 for 循环返回数字列表的总和。
I just know the following:
我只知道以下几点:
sum = 0
for x in [1,2,3,4,5]:
sum = sum + x
print(sum)
采纳答案by jonrsharpe
I think what you mean is how to encapsulate that for general use, e.g. in a function:
我认为您的意思是如何将其封装为一般用途,例如在函数中:
def sum_list(l):
sum = 0
for x in l:
sum += x
return sum
Now you can apply this to any list. Examples:
现在您可以将其应用于任何列表。例子:
l = [1, 2, 3, 4, 5]
sum_list(l)
l = list(map(int, input("Enter numbers separated by spaces: ").split()))
sum_list(l)
But note that sum
is already built in!
但请注意,sum
它已经内置了!
回答by zbs
l = [1,2,3,4,5]
sum = 0
for x in l:
sum = sum + x
And you can change l for any list you want.
你可以为你想要的任何列表更改 l 。
回答by Nandha Kumar
x=[1,2,3,4,5]
sum=0
for s in range(0,len(x)):
sum=sum+x[s]
print sum