【发布时间】:2018-07-07 21:51:21
【问题描述】:
我最近一直在研究我的生成器函数和表达式,但我不太确定如何解决这个问题。我如何使用生成器函数来生成然后按顺序打印值?
我使用 pythons 列表构建了我的 BST
bst = [20, [10, [5, [2, [], []], [8, [], []]], [15, [], []]], [30, [25, [22, [], []], [27, [], []]], [35, [], [37, [], []]]]]
如果我要打印中序遍历,我没有问题。因此,如果我要为以下功能调用 inorder(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))
它不是迭代整个函数 yield ,而是在它开始之前简单地停止迭代。
20
Traceback (most recent call last):
File "functionGenerator.py", line 64, in <module>
print(next(test))
StopIteration
我需要做什么才能使我的函数发生器正常运行?
【问题讨论】:
-
您的语法错误与生成器无关,您在 Python 3 中使用的是 Python 2 语法。
-
好吧,python 3 的语法会变成什么样子?
-
print(next(test)) -
您在原来的
inorder()实现中使用它... -
您的递归
inorder()但是还有其他问题;您需要使用yield from inorder(tree[1])或for res in inorder(tree[1]): yield res。