您的位置:首页 > 编程语言 > Python开发

迭代器就是重复地做一些事情,可以简单的理解为循环,在python中实现了__iter__方法的对象是可迭代的,实现了next()方法的对象是迭代器,这样说起来有

2015-02-06 15:59 1461 查看
迭代器就是重复地做一些事情,可以简单的理解为循环,在python中实现了__iter__方法的对象是可迭代的,实现了next()方法的对象是迭代器,这样说起来有点拗口,实际上要想让一个迭代器工作,至少要实现__iter__方法和next方法。很多时候使用迭代器完成的工作使用列表也可以完成,但是如果有很多值列表就会占用太多的内存,而且使用迭代器也让我们的程序更加通用、优雅、pythonic。下边是一个例子,从里边你会感受到不用列表而用迭代器的原因。
#!/usr/bin/env python

#coding=utf-8

class Fib:

def __init__(self):

self.a,self.b = 0,1

def next(self):

self.a,self.b = self.b,self.a+self.b

return self.a

def __iter__(self):

return self

fibs = Fib()

for f in fibs:

if f < 10000:

print f

else:

break

[/code]

迭代器是一个对象,而生成器是一个函数,迭代器和生成器是python中两个非常强大的特性,编写程序时你可以不使用生成器达到同样的效果,但是生成器让你的程序更加pythonic。创建生成器非常简单,只要在函数中加入yield语句即可。函数中每次使用yield产生一个值,函数就返回该值,然后停止执行,等待被激活,被激活后继续在原来的位置执行。下边的例子实现了同样的功能:

#!/usr/bin/env python

#coding=utf-8

def fib():

a,b = 0,1

while 1:

a,b = b,a+b

yield a

for f in fib():

if f < 10000:

print f

else:

break




生成器接收参数实例:

def counter(start_at):

count = start_at

while True:

print 'before count %s' % count

val = (yield count)

print 'after count %s, val %s' % (count, val)

if val is not None:

count = val

print 'sts a'

else:

count += 1

print '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', s

print 'calling count.next():', count.next()

print 'calling count.close():', count.close()

print 'calling count.next():', count.next()

[/code]

结果:

calling1 count.next(): before count 5

5

calling2 count.next(): after count 5, val None

sts b

before count 6

6

calling3 count.next(): after count 6, val None

sts b

before count 7

7

calling4 count.next(): after count 7, val None

sts b

before count 8

8

calling5 count.next(): after count 8, val None

sts b

before count 9

9

-------start---------

after count 9, val 20

sts a

before count 20

s 20

calling count.next(): after count 20, val None

sts b

before count 21

21

calling count.close(): None

calling count.next():

Traceback (most recent call last):

File "D:\Python27\counter.py", line 26, in <module>

print 'calling count.next():', count.next()

StopIteration

[/code]

来自为知笔记(Wiz)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐