简体   繁体   中英

Python: how to calculate the sum of a list without creating the whole list first?

Usually we have to (1) declare a list (2) calculate a sum of this list using sum()

But now I wish to specify a list start with 1 and interval 4, 100 elements, like this:

[1,5,9,13,17,21,25,29,33,37,…]

I don't want to envolve mathematical formula, so

(1) How to get the sum without even declaring this list?

(2) How to quickly get sum from 101st element to 200th element of this list?

The built-in class range does does exactly what you want in Python 3. In Python 2, use xrange . instead. For example:

for i in range(1, 401, 4): ... 

The range object does not contain a full list. It records only the start, end and step size. The iterator will also record the current position.

It is important to use xrange in Python 2 because the range function will return the entire list, which is exactly the opposite of what you want.

a = range(1, 401, 4)
sum(a) 

will compute the sum you want and allow you to reuse a afterwards.

A note on the number 401

The end of a range is exclusive. There are a couple of common formulas to get the correct number of elements in the range. start + count * step is the one I have chosen here because it is the easiest. It is also the largest number that will give count rather than count + 1 elements to the range. start + (count - 1) * step + 1 is the formula for the smallest number that will give you count elements. Since you want 100 elements, an end value of 398, 399, or 400 would give you the same result as 401.

Simply use itertools.count to get a counter and itertools.islice to get the required number of elements (you can iterate these instances but they don't create a list!):

>>> from  itertools import count, islice
>>> sum(islice(count(1, step=4), 100))  # get the first 100 elements and sum them
19900

The islice also supports start/stop:

>>> sum(islice(count(1, step=4), 101, 200))  # 101st element to 200th
59499

You can use generators with sum to avoid creating a list at first:

result = sum(x for x in range(1, 401, 4))

As @Mad Physicist mentioned in the comment, you don't even need the x for x part:

result = sum(range(1, 401, 4))

You can write a generator:

def ir(start=1, end=400, step=4):
    while True:
        yield start
        start+=step
        if start>=end: break

Or, if you want a specific number of elements:

def ir(start=1, n=100, step=4):
    cnt=0
    while True:
        yield start
        cnt+=1
        start+=step
        if cnt>=n: break

And then sum that:

 >>> sum(ir())
 19900

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM