basic understanding about yield
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | def merge2(iter1,iter2): """ on input iter1, iter2, two non-empty sorted iterators, not necessarily infinite, produces the sorted merge of the two iterators""" left=next(iter1) right=next(iter2) while True: if left<right: yield(left) try: left=next(iter1) except StopIteration: # iter1 is exhausted yield(right) # in my question I refer to this yield for right in iter2: yield(right) break else: yield(right) try: right=next(iter2) except StopIteration: # iter2 is exhausted yield(left) for left in iter1: yield(left) break |
在使用了
当再次调用迭代器的"next"方法(
实际上,yield表现为一个表达式,如果外部函数不调用
(关于代码对象、本地变量和全局变量的信息,运行的行保存在"堆栈帧"对象中,在Python中,它甚至可以作为任何其他对象进行寻址和自省)