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

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: