← 中文资源

简体中文版本

itertools.tee 把一个迭代器分成两支

tee 把单遍迭代器复制成多个独立游标,每支都能看到完整流;一支多读的部分会被缓冲等另一支追上,而父迭代器本身会被 tee 耗尽,只能驱动分支。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

historian: ['boot', 'login']
auditor: ['boot', 'login', 'deploy', 'logout']
parent remaining: []
b fully drained: [1, 2, 3, 4, 5]
a still intact: [1, 2, 3, 4, 5]

实现说明

events 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 演示输出是带标签的(historian:、auditor:、parent remaining:),每个操作都会留下自己的一行标注。

常见问题

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。 全部导入都来自标准库:itertools。 文件的状态由几个模块级绑定持有:events。

代码示例

from itertools import tee

events = iter(["boot", "login", "deploy", "logout"])

# tee splits one single-pass iterator into independent cursors.
historian, auditor = tee(events)

# Branch 1 pulls the first two events off its own cursor...
print("historian:", [next(historian) for _ in range(2)])

# ...while branch 2 still yields the full stream: tee buffers items
# one branch reads until the other catches up.
print("auditor:", list(auditor))

# tee itself exhausts the source iterator; drive the branches, not the parent.
print("parent remaining:", list(events))

# Drain order does not matter: whatever one branch read is buffered for the other.
a, b = tee([1, 2, 3, 4, 5])
print("b fully drained:", list(b))
print("a still intact:", list(a))