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 requests
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'保定'))
print(getWeather(u'长春'))
import requests
from 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了