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

案例


某軟件要求,從網絡抓去各個城市氣溫信息,并依次顯示:
北京: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)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容