← 中文资源

简体中文版本

itertools 惰性分批

用 itertools.batched 对任意可迭代对象惰性分批:大数据流过固定大小的批次,无需物化整个列表,附 3.12 前手写等价物。

阅读英文原文

实现说明

itertools 惰性分批以函数 endless_ids、batched_manual为骨架。 这个文件只在 while True 里循环。

使用要点

  • 跑完文件,输出里会留下标记——batch of。

常见问题

运行「itertools 惰性分批」会打印什么?

运行文件本身,batch of 这些前缀各对应一段演示逻辑。

签名一览:def endless_ids(start: int = 0)

核心语句

def endless_ids(start: int = 0):
    """模拟无限数据源。"""
    n = start
    while True:
        yield n
        n += 1
def batched_manual(iterable, n):
    it = iter(iterable)
    while True:
        chunk = tuple(islice(it, n))
        if not chunk:
            return
        yield chunk

代码示例

from itertools import batched, islice


def endless_ids(start: int = 0):
    """模拟无限数据源。"""
    n = start
    while True:
        yield n
        n += 1


if __name__ == '__main__':
    # batched(3.12+)惰性产出定长元组,最后一批可短
    source = endless_ids()
    for batch in batched(islice(source, 107), 25):
        print(f'batch of {len(batch)}: {batch[0]}..{batch[-1]}')

    # 手写等价物(3.12 之前):zip 严格模式 + 迭代器切片
    def batched_manual(iterable, n):
        it = iter(iterable)
        while True:
            chunk = tuple(islice(it, n))
            if not chunk:
                return
            yield chunk

    manual = list(batched_manual(range(7), 3))
    print(manual)