如何在python中对数字列表求和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17472771/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:18:10  来源:igfitidea点击:

How to sum a list of numbers in python

pythonnumberssum

提问by FZEROX

So first of all, I need to extract the numbers from a range of 455,111,451, to 455,112,000. I could do this manually, there's only 50 numbers I need, but that's not the point.

所以首先,我需要从 455,111,451 到 455,112,000 范围内提取数字。我可以手动执行此操作,我只需要 50 个数字,但这不是重点。

I tried to:

我试过了:

for a in range(49999951,50000000):
print +str(a)

What should I do?

我该怎么办?

采纳答案by Inbar Rose

Use sum

sum

>>> sum(range(49999951,50000000))
2449998775L


It is a builtin function, Which means you don't need to import anything or do anything special to use it. you should always consult the documentation, or the tutorials before you come asking here, in case it already exists - also, StackOverflow has a search function that could have helped you find an answer to your problem as well.

它是一个内置函数,这意味着你不需要导入任何东西或做任何特殊的事情来使用它。在您来这里询问之前,您应该始终查阅文档或教程,以防它已经存在 - 此外,StackOverflow 有一个搜索功能也可以帮助您找到问题的答案。



The sumfunction in this case, takes a list of integers, and incrementally adds them to eachother, in a similar fashion as below:

sum在这种情况下,该函数采用一个整数列表,并以类似的方式将它们彼此递增地相加,如下所示:

>>> total = 0
>>> for i in range(49999951,50000000):
    total += i

>>> total
2449998775L

Also - similar to Reduce:

也 - 类似于Reduce

>>> reduce(lambda x,y: x+y, range(49999951,50000000))
2449998775L

回答by Moh Zah

I haven't got your question well if you want to have the sum of numbers

如果你想得到数字的总和,我还没有很好地回答你的问题

sum = 0
for a in range(x,y):
    sum += a
print sum

if you want to have numbers in a list:

如果您想在列表中包含数字:

lst = []
for a in range(x,y):
    lst.append(a)
print lst

回答by Jon Clements

sumis the obvious way, but if you had a massive range and to compute the sum by incrementing each number each time could take a while, then you can do this mathematically instead (as shown in sum_range):

sum是显而易见的方法,但是如果您有一个很大的范围并且每次通过增加每个数字来计算总和可能需要一段时间,那么您可以用数学方法来代替(如 所示sum_range):

start = 49999951
end = 50000000

total = sum(range(start, end))

def sum_range(start, end):
    return (end * (end + 1) / 2) - (start - 1) * start / 2

print total
print sum_range(start, end)

Outputs:

输出:

2449998775
2499998775