我有一个简单的树类,我需要能够仅迭代叶节点。
我将数据添加到我的树中,如下所示:
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/