Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何使用python生成器递归地生成对象?_Python 3.x_Recursion_Generator_Yield_Yield From - Fatal编程技术网

Python 3.x 如何使用python生成器递归地生成对象?

Python 3.x 如何使用python生成器递归地生成对象?,python-3.x,recursion,generator,yield,yield-from,Python 3.x,Recursion,Generator,Yield,Yield From,我正在编写一个生成器函数,递归遍历给定星形节点的所有子节点 在下面的示例中,节点是一个星形functiondef节点。 node.getchildren()返回节点中包含子节点的生成器 我的目标是生成包含的每个节点。(即使在子节点中) 这里,如果我已经注释掉了收益率声明。 对于print语句,我得到了期望的结果,但如果我产生了节点,我就没有得到期望的输出 要复制此文件: -安装星体 import astroid node = astroid.extract_node(''' def test_

我正在编写一个生成器函数,递归遍历给定星形节点的所有子节点

在下面的示例中,
节点
是一个星形
functiondef
节点。
node.getchildren()
返回节点中包含子节点的生成器

我的目标是生成包含的每个节点。(即使在子节点中)

这里,如果我已经注释掉了收益率声明。 对于print语句,我得到了期望的结果,但如果我产生了节点,我就没有得到期望的输出

要复制此文件: -安装星体

import astroid

node = astroid.extract_node('''
def test_function(something): #@
    """Test function for getting subnodes"""
    assign_line = "String"
    ctx = len(assign_line)
    if ctx > 0:
        if ctx == 1:
            return 1
        if ctx > 10:
            return "Ten"
    else:
        return 0
''')

您可以递归地
将函数映射到child,并使用
生成:

def recursive_walk(node):
    # yield the base node
    yield node
    # for each of the recursive calls yield the remaining ones
    yield from map(recursive_walk, node.get_children())
如果他们没有孩子,那就什么也不生,继续下一个孩子

def recursive_walk(node):
    """
    Generator function to recursively walk through a given node.

    Yields every astroid node inside.
    """
    try:
        for subnode in node.get_children():
            yield subnode
            yield from recursive_walk(subnode)

    except (AttributeError, TypeError):
        yield node

因为你是新的,你可以考虑阅读:快乐编码!当然一个后续问题:在输出中,我得到的是基本节点和其他生成器对象,这不是我需要的。是否有一种方法可以从这些生成器对象中检索所有节点,这样我就可以只使用一个函数来生成所有节点?您只需要调用
列表(recursice\u walk(base\u node))
来检索所有节点。输出:
[,,,,,,,]
让我编辑我的问题并添加更多细节供您重现。我有一个错误
回溯(最近一次调用):文件“main.py”,第5行,在node=astroid.extract\u node(“”“AttributeError:模块”astroid“没有属性”extract\u node“
奇怪。请参阅最后一节
def recursive_walk(node):
    """
    Generator function to recursively walk through a given node.

    Yields every astroid node inside.
    """
    try:
        for subnode in node.get_children():
            yield subnode
            yield from recursive_walk(subnode)

    except (AttributeError, TypeError):
        yield node