简体   繁体   中英

yield from two generators at the same time, and make the result a tuple

I'm trying to know if there's a pythonic way to unroll two generators at the same time:

eg I have two files with the same number of lines. Of course, I could zip the lines after reading their entire content.

But is it possible to yield elements from the two generators at the same time ? when I try to run such code, it complains:

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

here, test and predict are two generators obtained by opening two files this way :

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)

I might be misunderstanding, but it sounds like you're looking for zip(). You can do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM