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

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

  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. class Fib:
  4. def __init__(self):
  5. self.a,self.b = 0,1
  6. def next(self):
  7. self.a,self.b = self.b,self.a+self.b
  8. return self.a
  9. def __iter__(self):
  10. return self
  11. fibs = Fib()
  12. for f in fibs:
  13. if f < 10000:
  14. print f
  15. else:
  16. break


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

 
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3. def fib():
  4. a,b = 0,1
  5. while 1:
  6. a,b = b,a+b
  7. yield a
  8. for f in fib():
  9. if f < 10000:
  10. print f
  11. else:
  12. break
  13. 生成器接收参数实例:
  14. def counter(start_at):
  15. count = start_at
  16. while True:
  17. print 'before count %s' % count
  18. val = (yield count)
  19. print 'after count %s, val %s' % (count, val)
  20. if val is not None:
  21. count = val
  22. print 'sts a'
  23. else:
  24. count += 1
  25. print 'sts b'
  26. if __name__ == '__main__':
  27. count = counter(5)
  28. print 'calling1 count.next():', count.next()
  29. print 'calling2 count.next():', count.next()
  30. print 'calling3 count.next():', count.next()
  31. print 'calling4 count.next():', count.next()
  32. print 'calling5 count.next():', count.next()
  33. print '-------start---------'
  34. s = count.send(20)
  35. print 's', s
  36. print 'calling count.next():', count.next()
  37. print 'calling count.close():', count.close()
  38. print 'calling count.next():', count.next()


  1. 结果:
  2. calling1 count.next(): before count 5
  3. 5
  4. calling2 count.next(): after count 5, val None
  5. sts b
  6. before count 6
  7. 6
  8. calling3 count.next(): after count 6, val None
  9. sts b
  10. before count 7
  11. 7
  12. calling4 count.next(): after count 7, val None
  13. sts b
  14. before count 8
  15. 8
  16. calling5 count.next(): after count 8, val None
  17. sts b
  18. before count 9
  19. 9
  20. -------start---------
  21. after count 9, val 20
  22. sts a
  23. before count 20
  24. s 20
  25. calling count.next(): after count 20, val None
  26. sts b
  27. before count 21
  28. 21
  29. calling count.close(): None
  30. calling count.next():
  31. Traceback (most recent call last):
  32. File "D:Python27counter.py", line 26, in <module>
  33. print 'calling count.next():', count.next()
  34. StopIteration





原文地址:https://www.cnblogs.com/highroom/p/f7a6f4237f5f5501c834b261f7a4c2f0.html