You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python gen_stream无限迭代器传入None时用for循环限制输出的方法

无限迭代器限制输出长度实现示例

当gen_stream的total参数设为None时,函数会返回无限迭代器,遍历完所有输入元素后会持续返回0,你可以通过for循环手动计数控制输出长度,也可以用标准库工具简化实现:

手动计数实现

# 先定义需要的提取器和测试数据,和之前示例一致
def day_extractor(x):
    months = [31, 28, 31, 30, 31, 31, 30, 31, 30, 31, 30, 31]
    acc = sum(months[:x[1] - 1]) + x[0] - 1
    return acc, x[2]

precipitation_days = [(3,1,4),(5,2,6)]
# 构造无限迭代器
infinite_stream = gen_stream(None, precipitation_days, day_extractor)

output = []
# 限定只输出前90天的降水数据
for idx, daily_precipitation in enumerate(infinite_stream):
    if idx >= 90:
        break
    output.append(daily_precipitation)

print(output)

用itertools.islice简化实现

如果不想手动写计数逻辑,可以直接用标准库的itertools.islice截断无限迭代器,效果和手动计数完全一致:

from itertools import islice

def day_extractor(x):
    months = [31, 28, 31, 30, 31, 31, 30, 31, 30, 31, 30, 31]
    acc = sum(months[:x[1] - 1]) + x[0] - 1
    return acc, x[2]

precipitation_days = [(3,1,4),(5,2,6)]
infinite_stream = gen_stream(None, precipitation_days, day_extractor)
# 直接截取前90个元素
output = list(islice(infinite_stream, 90))

print(output)

以上两种实现均可按需调整终止条件的数值,自定义需要的输出长度。

内容的提问来源于stack exchange,提问作者Skeptic_0286

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 19:00:02