保持提供给生成器的输入

问题描述 投票:0回答:0

假设我有一个生成器

gen
生成项目,另一个生成器
trans
转换项目并为每个输入项返回一个输出项,并假设两个生成器都很昂贵并且我不能更改它们中的任何一个。
gen
的输出被馈送到
trans
,但是当循环
trans
的结果时,我也需要
gen
的相应输出。我目前的解决方案是
tee(gen())
然后
zip
trans
的输出,这很好用,但我的问题是是否有更好的解决方案我错过了?

from itertools import tee

# these two generators are just an example, assume these are expensive and can't be changed
def gen():
    yield from range(3)
def trans(inp):
    for x in inp:
        yield chr(x + ord("A"))

# my question is: is there a better way to achieve what the following two lines are doing?
g1, g2 = tee(gen())
for i, o in zip(g1, trans(g2)):
    print(f"{i} -> {o}")
python python-3.x generator
© www.soinside.com 2019 - 2024. All rights reserved.