如何在更改与之相关联的变量时保留一个Python生成器的状态?

2024-04-20 07:22:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图遍历一棵树,迭代到一个叶,然后返回到根节点,向下迭代到下一个叶,直到到达树的末尾。你知道吗

当我将当前节点重置为根节点时,生成器表达式将重置,如何保留它?你知道吗

class New_node(object):
    def __init__(self, data=''):
        self.data = data
        self.children = []

    def add_child(self, obj):
        self.children.append(obj)

    def child_data(self):
        return [c.data for c in self.children]

    def select_child(self, letter):
        return self.children[self.child_data().index(letter)]

    def next_child(self):
        for c in self.children:
            yield c

for c in node.child_data()
    ...
    ...
    ...
    try:
        node = node.next_child().next()
    except StopIteration:
        node = root

Tags: inselfnodechildobjfordatareturn
2条回答

函数中的yield语句使其成为生成器。所以next_child方法是一个生成器。生成器通常用于for循环。
要使生成器中的下一个元素脱离for循环,请初始化生成器并对其调用next函数。你知道吗

child = node.next_child().next

for c in node.child_data()
    ...
    ...
    ...
    try:
        node = child()
    except StopIteration:
        node = root

我不太清楚您在for循环中到底在做什么,但是这里有一个生成器方法可以迭代。你知道吗

def traverse(self, ancestors=list()):
    if self.children:
        for c in self.children:
            c.traverse(ancestors+[self])
    else:
        for a in ancestors:
            yield a
        yield self

相关问题 更多 >