Python:如何在不先创建整个列表的情况下计算列表的总和? [英] Python: how to calculate the sum of a list without creating the whole list first?
问题描述
通常,我们必须(1)声明一个列表(2)使用sum()
Usually we have to (1) declare a list (2) calculate a sum of this list using sum()
但是现在我希望指定一个列表,该列表以1开头,间隔4为100个元素,例如:
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)如何在不声明此列表的情况下获得总和?
(1) How to get the sum without even declaring this list?
(2)如何快速从此列表的第101个元素到第200个元素求和?
(2) How to quickly get sum from 101st element to 200th element of this list?
推荐答案
只需使用 itertools.islice
获取所需数量的元素(您可以迭代这些实例,但它们不会创建列表!):
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
islice
还支持开始/停止:
>>> sum(islice(count(1, step=4), 101, 200)) # 101st element to 200th
59499
这篇关于Python:如何在不先创建整个列表的情况下计算列表的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!