python - 如何在 Python 中加入两个生成器?

我想更改以下代码

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

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

到此代码:

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

我得到错误:

unsupported operand type(s) for +: 'generator' and 'generator'

如何在 Python 中加入两个生成器?

最佳答案

itertools.chain()应该这样做。它需要多个迭代器,并从一个一个地产生,大致相当于:

def chain(*iterables):
    for it in iterables:
        for element in it:
            yield element

使用示例:

from itertools import chain

g = (c for c in 'ABC')  # Dummy generator, just for example
c = chain(g, 'DEF')  # Chain the generator and a string
for item in c:
    print(item)

输出:

A
B
C
D
E
F

https://stackoverflow.com/questions/3211041/

相关文章:

python - 如何在不导入的情况下检查 Python 模块是否存在

linux - 如何在不重新输入 SSH 密码的情况下执行 `git pull`?

python - 是否有可能 "hack"Python 的打印功能?

linux - 什么包包括 AB Ubuntu 中的 Apache 服务器基准测试工具

python - pandas loc vs. iloc vs. at vs. iat?

android - adb 不显示 nexus 5 设备

python - Seaborn地 block 没有出现

installation - 如何从命令行正确设置 CMAKE_INSTALL_PREFIX

python - bs4.FeatureNotFound : Couldn't find a tre

python - numpy.where() 详细的分步说明/示例