迭代器就是重复地做一些事情,可以简单的理解为循环,在python中实现了__iter__方法的对象是可迭代的,实现了next()方法的对象是迭代器,这样说起来有
迭代器就是重复地做一些事情,可以简单的理解为循环,在python中实现了__iter__方法的对象是可迭代的,实现了next()方法的对象是迭代器,这样说起来有点拗口,实际上要想让一个迭代器工作,至少要实现__iter__方法和next方法。很多时候使用迭代器完成的工作使用列表也可以完成,但是如果有很多值列表就会占用太多的内存,而且使用迭代器也让我们的程序更加通用、优雅、pythonic。下边是一个例子,从里边你会感受到不用列表而用迭代器的原因。
#!/usr/bin/env python#coding=utf-8class Fib:def __init__(self):self.a,self.b = 0,1def next(self):self.a,self.b = self.b,self.a+self.breturn self.adef __iter__(self):return selffibs = Fib()for f in fibs:if f < 10000:print felse:break
迭代器是一个对象,而生成器是一个函数,迭代器和生成器是python中两个非常强大的特性,编写程序时你可以不使用生成器达到同样的效果,但是生成器让你的程序更加pythonic。创建生成器非常简单,只要在函数中加入yield语句即可。函数中每次使用yield产生一个值,函数就返回该值,然后停止执行,等待被激活,被激活后继续在原来的位置执行。下边的例子实现了同样的功能:
#!/usr/bin/env python#coding=utf-8def fib():a,b = 0,1while 1:a,b = b,a+byield afor f in fib():if f < 10000:print felse:break生成器接收参数实例:def counter(start_at):count = start_atwhile True:print 'before count %s' % countval = (yield count)print 'after count %s, val %s' % (count, val)if val is not None:count = valprint 'sts a'else:count += 1print 'sts b'if __name__ == '__main__':count = counter(5)print 'calling1 count.next():', count.next()print 'calling2 count.next():', count.next()print 'calling3 count.next():', count.next()print 'calling4 count.next():', count.next()print 'calling5 count.next():', count.next()print '-------start---------'s = count.send(20)print 's', sprint 'calling count.next():', count.next()print 'calling count.close():', count.close()print 'calling count.next():', count.next()
结果:calling1 count.next(): before count 55calling2 count.next(): after count 5, val Nonests bbefore count 66calling3 count.next(): after count 6, val Nonests bbefore count 77calling4 count.next(): after count 7, val Nonests bbefore count 88calling5 count.next(): after count 8, val Nonests bbefore count 99-------start---------after count 9, val 20sts abefore count 20s 20calling count.next(): after count 20, val Nonests bbefore count 2121calling count.close(): Nonecalling count.next():Traceback (most recent call last):File "D:\Python27\counter.py", line 26, in <module>print 'calling count.next():', count.next()StopIteration
浙公网安备 33010602011771号