首页 > 编程 > Python > 正文

python特性(七):通过生成器函数构造序列对象的迭代器

2019-11-08 01:37:22
字体:
来源:转载
供稿:网友

在前面的博文中介绍过如何构造序列对象的迭代器。本文将通过生成器函数来重写这篇博文的代码。

事实上,一个序列对象的迭代器,依赖于一个整数序列的迭代器。看下面的代码。

def MyGenerator(len):    start  = 0    while start < len:        yield start        start = start + 1gen = MyGenerator(3)PRint gen.next()print gen.next()print gen.next()print gen.next()当调用第1次next方法时, 会首先执行MyGenerator方法的第1行代码start = 0。然后进入循环。这里len的值通过参数传入为3。因此while的条件表达式为真。进入循环后,遇到yield语句,方法的执行过程被挂起。next方法的返回值为start的值,即0。

当调用第2次next方法时,接着上面的挂起点,往下执行start = start + 1语句,start的值变为1。接着又进入while循环的条件判断,start<len依然为真。因此,又执行yield语句。但是由于start值为1,故而这一次next方法返回的值为1。

第3次next方法的调用类似。

当调用第4次next方法时,while循环的条件判断start < len为假,while循环结束,MyGenerator方法调用也随之结束,抛出StopIteration异常。

输出结果

012Traceback (most recent call last):  File "test.py", line 21, in <module>    print gen.next()StopIteration有了上面的结果,重写序列对象的迭代器轻而易举。

def MyGenerator(sequence):    start  = 0    while start < len(sequence):        yield sequence[start]        start = start + 1gen = MyGenerator([1,2,3,'a','b','c'])for i in gen:    print i对比之前迭代器类的代码,我们可以认识到,yield关键字为构造迭代器提供了多大的方便。它使得代码长度缩减许多,同时也大大增强了可读性。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表