Python: 如何在不先创建整个列表的情况下计算列表的总和?

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

通常我们必须 (1) 声明一个列表 (2) 使用 sum()

计算这个列表的总和

但现在我想指定一个以 1 开始,间隔 4,100 个元素的列表,像这样:

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

我不想涉及数学公式,所以

(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?

您可以将生成器与 sum 一起使用,以避免首先创建列表:

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

正如@Mad Physicist 在评论中提到的,您甚至不需要 x for x 部分:

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

built-in class range does does exactly what you want in Python 3. In Python 2, use xrange。反而。例如:

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

range 对象不包含完整列表。它只记录开始、结束和步长。迭代器也会记录当前位置。

在Python 2 中使用xrange 很重要,因为范围函数将return 整个列表,这与您想要的正好相反。

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

将计算您想要的总和并允许您在之后重复使用 a

关于401号的备注

范围的结尾是排他性的。有几个常用公式可用于获取范围内元素的正确数量。 start + count * step是我在这里选择的,因为它是最简单的。它也是给范围提供 count 而不是 count + 1 元素的最大数字。 start + (count - 1) * step + 1 是为您提供 count 个元素的最小数字的公式。由于您需要 100 个元素,因此最终值为 398、399 或 400 会得到与 401 相同的结果。

你可以写一个生成器:

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

或者,如果您想要特定数量的元素:

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

然后求和:

 >>> sum(ir())
 19900

只需使用 itertools.count to get a counter and itertools.islice 即可获得所需数量的元素(您可以迭代这些实例,但它们不会创建列表!):

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

islice也支持start/stop:

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