How to join two generators in Python?

后端 未结 12 1523
醉酒成梦
醉酒成梦 2020-11-28 22:40

I want to change the following code

for directory, dirs, files in os.walk(directory_1):
    do_something()

for directory, dirs, files in os.walk(directory_2         


        
12条回答
  •  粉色の甜心
    2020-11-28 23:33

    Lets say that we have to generators (gen1 and gen 2) and we want to perform some extra calculation that requires the outcome of both. We can return the outcome of such function/calculation through the map method, which in turn returns a generator that we can loop upon.

    In this scenario, the function/calculation needs to be implemented via the lambda function. The tricky part is what we aim to do inside the map and its lambda function.

    General form of proposed solution:

    def function(gen1,gen2):
            for item in map(lambda x, y: do_somethin(x,y), gen1, gen2):
                yield item
    

提交回复
热议问题