python - 如何返回一个值,但继续执行

标签 python python-3.x

我有一个简单的树类,我需要能够仅迭代叶节点。

我将数据添加到我的树中,如下所示:

p = ParamTree()
p.add('system.screen.timeout')
p.add('system.screen.lock.enabled')
p.add('system.screen.lock.code')

我希望能够按顺序获得超时启用代码

如果我编写一个函数来打印值,它会按预期工作:

def print_nodes(tree):
    for node in tree.nodes:
        if node.has_children():
            print_nodes(node)
        else:
            print(node)

输出:

>>> print_nodes(p)
timeout
enabled
code

我将如何实现一个具有相同功能的生成器?我尝试用 yield 替换 print(),但它不起作用。

def yield_nodes(tree):
    for node in tree.nodes:
        if node.has_children():
            yield_nodes(node)
        else:
            yield node

输出:

>>> g = yield_nodes(p)
>>> for n in g:
...   print(n)
...
>>>

最佳答案

我假设您的 yield_nodes 生成器编写如下:

def yield_nodes(tree):
    for node in tree.nodes:
        if node.has_children():
            yield_nodes(node)
        else:
            yield node

正如您可能注意到的,调用 yield_nodes 返回一个生成器(您可以迭代它),但您实际上并没有用它做任何事情。我建议的解决方案如下:

def yield_nodes(tree):
    for node in tree.nodes:
        if node.has_children():
            yield from yield_nodes(node)
        else:
            yield node

关于python - 如何返回一个值,但继续执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42691544/

相关文章:

python - 如何在 Python 中创建三元等高线图?

python - 如何在 Python 中从 3 个列表创建 3 维字典

python - 禁用编辑 QLineEdit

Python 检查模块 : keyword only args

python - 为什么 django 的 create_user 方法不验证唯一性?

python - 以 epsilon 精度将 Pandas DataFrame 条件转换为负数、零数和正数

python - 使用 Beautiful Soup 将多个类提取到 pandas 数据框中

python - python字符串之前的b前缀是什么意思?

python - 使用 Python 解析电子邮件

python - threading.Thread 的 setDaemon() 方法