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 返回當前的迭代值。
新聞熱點
疑難解答