python的可迭代對象:list(列表)是可迭代對象,dict(字典)是可迭代對象,string(字串)也是可迭代對象。l = [1,2,3,4]s = 'abcdef'for x in l:print(x)for x in s:print(x)print(iter(l))print(iter(s))
可以由python的內建函數iter得到一個迭代器對象
數組和字串都可以得到一個迭代器對象。
參數要麼支援迭代器,要麼是一個序列
其實,原因是這些迭代器對象都滿足迭代協議的介面;我們調用iter()方法,實際上是調用了l.iter()的方法
而s.getitem是一個序列介面;
列表迭代完畢拋出異常。
所以,for x in l:print(x)的工作機制先由iter(l)得到一個迭代器,就是不停的調用next(),直到拋出異常。
注意可迭代對象和迭代器對象的區別
下面說說一下問題的解決方案
ImportError: No module named 'requests'
requests下載地址
然後pip install 包名
import requestsdef 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'保定'))print(getWeather(u'長春'))
import requestsfrom collections import Iterable,Iterator# 氣溫迭代器class 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']) # next調用getWeather方法 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'湘潭']): # x就是getWeather return的結果 print(x)
python3,next變成next了