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

如何实现每次返回固定宽度循环切片字符串的Python无限iterator/generator

无限循环滑动切片生成器实现

最简无依赖版本(模运算实现)

无需导入任何模块,逻辑清晰兼容性好:

def my_iter(s, d):
    n = len(s)
    offset = 0
    while True:
        yield ''.join(s[(offset + k) % n] for k in range(d))
        offset += 1

基于itertools.cycle的实现(匹配你提到的思路)

利用cycle生成无限循环的字符迭代器,配合滑动窗口取固定长度内容:

from itertools import cycle
def my_iter(s, d):
    char_cycle = cycle(s)
    # 初始化首个窗口
    window = [next(char_cycle) for _ in range(d)]
    yield ''.join(window)
    while True:
        # 窗口向右滑动1位
        window.pop(0)
        window.append(next(char_cycle))
        yield ''.join(window)

超短实现(适合短字符串场景)

通过重复字符串规避模运算,代码极精简,长字符串场景下内存效率较低:

def my_iter(s, d):
    i = 0
    while True:
        yield (s * ((i + d) // len(s) + 1))[i:i+d]
        i += 1

测试验证

使用你提供的调用代码运行,输出和预期完全一致:

s = '123456789 '
it = my_iter(s, 9)
print(next(it))
print(next(it))
print(next(it))
print(next(it))

输出结果:

123456789
23456789 
3456789 1
456789 12

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 01:27:03