同时从两个发电机产生,并使结果成为元组

时间:2015-08-04 22:01:42

标签: python generator

我试图知道是否有同时展开两台发电机的pythonic方法:

e.g。我有两个行数相同的文件。当然,我可以在阅读完整篇文章后拉链。

但是有可能同时从两个发电机产生元件吗? 当我尝试运行这样的代码时,它会抱怨:

return (yield from test, yield from predict)
                       ^
SyntaxError: invalid syntax

这里,testpredict是通过这种方式打开两个文件获得的两个生成器:

with open(test_filename,"rt") as test:
    with open(predict_filename,"rt") as predict:
        for couple in yield_couples(test,predict):
            do_something(couple)

def yield_couples(test,predict,category):

    return (yield from test, yield from predict)

1 个答案:

答案 0 :(得分:1)

我可能会误解,但听起来你正在寻找zip()。你可以这样做:

with open(test_filename,"rt") as test:
    with open(predict_filename,"rt") as predict:
        for couple in zip(test,predict):
            do_something(couple)