美文网首页
python(可迭代对象和迭代器对象)

python(可迭代对象和迭代器对象)

作者: OldSix1987 | 来源:发表于2016-09-02 17:55 被阅读448次

    案例


    某软件要求,从网络抓去各个城市气温信息,并依次显示:
    北京:15~20
    天津:17~22
    长春:12~18
    ……
    如果一次抓取所有城市天气再显示,显示第一个城市气温时,有很高的延时,并且浪费存储空间。
    我们期望以“用时访问”的策略,并且能把所有城市气温封装到一个对象里,可用for语句进行迭代。如何解决?

    解析


    Step1:实现一个迭代器对象WeatherIterator,__next__方法每次返回一个城市气温。
    Step2:实现一个可迭代对象Weatherlterable,__iter__方法返回一个迭代器对象。

    # coding:utf8
    
    from collections import Iterable, Iterator
    import requests
    
    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'])
    
        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)
    

    相关文章

      网友评论

          本文标题:python(可迭代对象和迭代器对象)

          本文链接:https://www.haomeiwen.com/subject/aizhettx.html