Python 有序遍历的生成函数

Python 有序遍历的生成函数,python,generator,Python,Generator,我最近一直在研究我的生成器函数和表达式,但我不太确定如何解决这个问题。如何使用生成器函数生成值,然后按顺序打印这些值 我使用pythons列表构建了我的BST bst = [20, [10, [5, [2, [], []], [8, [], []]], [15, [], []]], [30, [25, [22, [], []], [27, [], []]], [35, [], [37, [], []]]]] 如果我要打印顺序遍历,我没有问题。因此,如果我要为以下函数调用inoder(bst):

我最近一直在研究我的生成器函数和表达式,但我不太确定如何解决这个问题。如何使用生成器函数生成值,然后按顺序打印这些值

我使用pythons列表构建了我的BST

bst = [20, [10, [5, [2, [], []], [8, [], []]], [15, [], []]], [30, [25, [22, [], []], [27, [], []]], [35, [], [37, [], []]]]]
如果我要打印顺序遍历,我没有问题。因此,如果我要为以下函数调用inoder(bst):

def inorder(tree):
    if tree:
        inorder(tree[1])
        print (tree[0])
        inorder(tree[2])
我得到这个输出

2
5
8
10
15
20
22
25
27
30
35
37
我认为生成器表达式同样简单

def inorder(tree):
    if tree:
        inorder(tree[1])
        yield (tree[0])
        inorder(tree[2])
我遇到的问题是让我的main遍历函数中生成的内容。我以为应该是这样的

test= inorder(bst)

for i in range(0,len(l)): # l is the number of items in bst
    print (next(test))
它不是迭代整个函数,而是在iterable开始之前停止它

    20
Traceback (most recent call last):
  File "functionGenerator.py", line 64, in <module>
    print(next(test))
StopIteration
20
回溯(最近一次呼叫最后一次):
文件“functionGenerator.py”,第64行,在
打印(下一个(测试))
停止迭代
我需要做什么才能使我的函数生成器正常工作

您的
inoorder()
实现没有正确地递归。您只打印树的当前顶部节点。这是因为只调用
inoorder(树[1])
inoorder(树[2])
返回一个生成器对象,而不是迭代这些生成器

使用

将生成器委托给另一个生成器,从该子生成器开始,直到完成为止。这样你就可以正确地递归

如果您使用的是较旧的Python版本(在Python 3.3之前),则需要手动迭代递归调用:

def inorder(tree):
    if tree:
        for sub in inorder(tree[1]):
            yield sub
        yield tree[0]
        for sub in inorder(tree[2]):
            yield sub
接下来,您可以迭代
inoorder()
生成器:

>>> for node in inorder(bst):
...     print(node)
...
2
5
8
10
15
20
22
25
27
30
35
37
尽管使用
next()
也可以:

>>> tree = inorder(bst)
>>> print(next(tree))
2
>>> print(next(tree))
5

但是迭代更干净,一旦启动了
StopIteration
,迭代就会自动停止。

您的语法错误与生成器无关,您在Python3中使用的是Python2语法。好吧,Python3语法会是什么样子?
print(next(test))
您在原始
inorder()中使用它
implementation…但是递归的
inoorder()
还有其他问题;您需要使用
yield from inorder(tree[1])
作为inorder(tree[1])中的res:yield res
。谢谢,我将确保在以后的问题中遵循最小的完整且可验证的示例。
>>> tree = inorder(bst)
>>> print(next(tree))
2
>>> print(next(tree))
5