且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-05 12:49:10

使用

>>>总和(范围(49999951,50000000))2449998775L

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

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

>>>总计 = 0>>>对于 i 在范围内(49999951,50000000):总计 += i>>>全部的2449998775L

也 - 类似于 Reduce:

>>>减少(λ x,y:x+y,范围(49999951,50000000))2449998775L

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.

I tried to:

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

What should I do?

Use 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, *** has a search function that could have helped you find an answer to your problem as well.


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

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

>>> total
2449998775L

Also - similar to Reduce:

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