How to join two generators in Python?

后端 未结 12 1520
醉酒成梦
醉酒成梦 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:30

    If you want to keep the generators separate but still iterate over them at the same time you can use zip():

    NOTE: Iteration stops at the shorter of the two generators

    For example:

    for (root1, dir1, files1), (root2, dir2, files2) in zip(os.walk(path1), os.walk(path2)):
    
        for file in files1:
            #do something with first list of files
    
        for file in files2:
            #do something with second list of files
    

提交回复
热议问题