How to sum a list of numbers in python

痞子三分冷 提交于 2019-12-12 12:15:32

问题


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?


回答1:


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, StackOverflow 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



回答2:


sum is 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):

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



回答3:


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


来源:https://stackoverflow.com/questions/17472771/how-to-sum-a-list-of-numbers-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!