How to sum a list of numbers in python

2019-06-28 02:21发布

问题:

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