Python 迭代器与生成器实例详解
一、如何实现可迭代对象和迭代器对象
1.由可迭代对象得到迭代器对象
例如l就是可迭代对象,iter(l)是迭代器对象
In [1]: l = [1,2,3,4]In [2]: l.__iter__Out[2]: <method-wrapper '__iter__' of list object at 0x000000000426C7C8>In [3]: t = iter(l)In [4]: t.next()Out[4]: 1In [5]: t.next()Out[5]: 2In [6]: t.next()Out[6]: 3In [7]: t.next()Out[7]: 4In [8]: t.next()---------------------------------------------------------------------------StopIteration Traceback (most recent call last)<ipython-input-8-3660e2a3d509> in <module>()----> 1 t.next()StopIteration:for x in l: print xfor 循环的工作流程,就是先有iter(l)得到一个t,然后不停的调用t.nex(),到最后捕获到StopIteration,就结束迭代
# 下面这种直接调用函数的方法如果数据量大的时候会对网络IO要求比较高,可以采用迭代器的方法
def getWeather(city): r = requests.get(u'http://wthrcdn.etouch.cn/weather_mini?city='+city) data = r.json()['data']['forecast'][0] return '%s:%s,%s' %(city, data['low'], data['high'])print getWeather(u'北京')返回值:
北京:低温 13℃,高温 28℃
实现一个迭代器对象WeatherIterator,next 方法每次返回一个城市气温
实现一个可迭代对象WeatherIterable,iter方法返回一个迭代器对象
# -*- coding:utf-8 -*-import requestsfrom collections import Iterable, Iteratorclass WeatherIterator(Iterator): def __init__(self, cities): self.cities = cities self.index = 0 def getWeather(self,city): r = requests.get(u'http://wthrcdn.etouch.cn/weather_mini?city='+city) data = r.json()['data']['forecast'][0] return '%s:%s,%s' %(city, data['low'], data['high']) def next(self): if self.index == len(self.cities): raise StopIteration city = self.cities[self.index] self.index += 1 return self.getWeather(city)class WeatherIterable(Iterable): def __init__(self, cities): self.cities = cities def __iter__(self): return WeatherIterator(self.cities)for x in WeatherIterable([u'北京',u'上海',u'广州',u'深圳']): print x.encode('utf-8')输出:北京:低温 13℃,高温 28℃上海:低温 14℃,高温 22℃广州:低温 17℃,高温 23℃深圳:低温 18℃,高温 24℃
二、使用生成器函数实现可迭代对象
1.实现一个可迭代对象的类,它能迭代出给定范围内所有素数
素数定义为在大于1的自然数中,除了1和它本身以外不再有其他因数的数称为素数。
一个带有 yield 的函数就是一个 generator,它和普通函数不同,生成一个 generator 看起来像函数调用,但不会执行任何函数代码,直到对其调用 next()(在 for 循环中会自动调用 next())才开始执行。虽然执行流程仍按函数的流程执行,但每执行到一个 yield 语句就会中断,并返回一个迭代值,下次执行时从 yield 的下一个语句继续执行。看起来就好像一个函数在正常执行的过程中被 yield 中断了数次,每次中断都会通过 yield 返回当前的迭代值。
新闻热点
疑难解答