How to join two generators in Python?

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

    2020 update: Work in both python 3 and python 2

    import itertools
    
    iterA = range(10,15)
    iterB = range(15,20)
    iterC = range(20,25)
    
    ### first option
    
    for i in itertools.chain(iterA, iterB, iterC):
        print(i)
    
    # 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
    
    ### alternative option, introduced in python 2.6
    
    for i in itertools.chain.from_iterable( [iterA, iterB, iterC] ):
        print(i)
    
    # 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
    

    itertools.chain() is the basic.

    itertools.chain.from_iterables is handy if you have an iterable of iterables. For example a list of files per subdirectory like [ ["src/server.py", "src/readme.txt"], ["test/test.py"] ].

提交回复
热议问题