python中的迭代器和生成器
2018-01-12 14:35
281 查看
一 概要
在了解Python的数据结构时,容器(container)、可迭代对象(iterable)、迭代器(iterator)、生成器(generator)、列表/集合/字典推导式(list,set,dict comprehension)众多概念参杂在一起,难免让初学者一头雾水,我将用一篇文章试图将这些概念以及它们之间的关系捋清楚def fab(max): n, a, b = 0, 0, 1 while n < max: print b a, b = b, a + b n = n + 1
直接在函数fab(max)中用print打印会导致函数的可复用性变差,因为fab返回None。其他函数无法获得fab函数返回的数列。
max(len(x.strip()) for x in open('/hello/abc','r'))
练习2:
import queue def tt(): for x in range(4): print ('tt'+str(x) ) yield def gg(): for x in range(4): print ('xx'+str(x) ) yield class Task(): def __init__(self): self._queue = queue.Queue() def add(self,gen): self._queue.put(gen) def run(self): while not self._queue.empty(): for i in range(self._queue.qsize()): try: gen= self._queue.get() gen.send(None) except StopIteration: pass else: self._queue.put(gen) t=Task() t.add(tt()) t.add(gg()) t.run() # tt0 # xx0 # tt1 # xx1 # tt2 # xx2 # tt3 # xx3
参考:
http://anandology.com/python-practice-book/iterators.html http://www.cnblogs.com/kaituorensheng/p/3826911.html http://www.jb51.net/article/80740.htm http://www.open-open.com/lib/view/open1463668934647.html
本文转自 http://www.cnblogs.com/yuanchenqi/articles/5769491.html
相关文章推荐
- python拗口语法点总计1:迭代器、生成器、元组
- Python: 迭代器与生成器小结
- python生成器,可迭代对象,迭代器区别和联系
- python014 Python3 迭代器与生成器
- Python3 迭代器与生成器
- python的迭代器iterator和生成器generator(关键字yield)的简单理解
- [Python] - 迭代器与生成器
- python 迭代器 生成器
- python-生成式、生成器、迭代器
- python——迭代器和生成器
- python的迭代器与生成器实例详解
- Python学习笔记010_迭代器_生成器
- Python数据类型,迭代器和生成器
- ·python·用生成器和迭代器实现自己的xrange
- python 迭代器和生成器
- Python基础-迭代器和生成器
- Python学习之路六---迭代器、生成器
- Python——迭代器和生成器
- python迭代器 生成器 装饰器
- Python生成器与迭代器