Adding elements to python generators

前端 未结 4 1608
醉酒成梦
醉酒成梦 2020-12-13 19:56

Is it possible to append elements to a python generator?

I\'m currently trying to get all images from a set of disorganized folders and write them to a new directory

相关标签:
4条回答
  • 2020-12-13 20:36

    You are looking for itertools.chain. It will combine multiple iterables into a single one, like this:

    >>> import itertools 
    >>> for i in itertools.chain([1,2,3], [4,5,6]):
    ...     print(i)
    ... 
    1
    2
    3
    4
    5
    6
    
    0 讨论(0)
  • 2020-12-13 20:44

    Like this.

    def threeGens( i, j, k ):
        for x in range(i):
           yield x
        for x in range(j):
           yield x
        for x in range(k):
           yield x
    

    Works well.

    0 讨论(0)
  • 2020-12-13 20:49

    This should do it, where directories is your list of directories:

    import os
    import itertools
    
    generators = [os.walk(d) for d in directories]
    for root, dirs, files in itertools.chain(*generators):
        print root, dirs, files
    
    0 讨论(0)
  • 2020-12-13 20:56
    def files_gen(topdir='.'):
        for root, dirs, files in os.walk(topdir):
            # ... do some stuff with files
            for f in files:
                yield os.path.join(root, f)
            # ... do other stuff
    
    for f in files_gen():
        print f
    
    0 讨论(0)
提交回复
热议问题