简体   繁体   English

将元素添加到 python 生成器

[英]Adding elements to python generators

Is it possible to append elements to a python generator?是否可以将元素附加到 python 生成器?

I'm currently trying to get all images from a set of disorganized folders and write them to a new directory.我目前正在尝试从一组杂乱无章的文件夹中获取所有图像并将它们写入新目录。 To get the files, I'm using os.walk() which returns a list of image files in a single directory.为了获取文件,我使用 os.walk() 返回单个目录中的图像文件列表。 While I can make a generator out of this single list, I don't know how to combine all these lists into one single generator.虽然我可以用这个单一的列表制作一个生成器,但我不知道如何将所有这些列表组合成一个单一的生成器。 Any help would be much appreciated.任何帮助将非常感激。

Related:有关的:

You are looking for itertools.chain .您正在寻找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

This should do it, where directories is your list of directories:这应该这样做,其中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
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

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.效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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