gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:34:23 24 4
gpt4 key购买 nike

通常我们必须 (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?

最佳答案

只需使用 itertools.count得到一个柜台和itertools.islice获取所需数量的元素(您可以迭代这些实例,但它们不会创建列表!):

>>> 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:如何在不先创建整个列表的情况下计算列表的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42059247/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com