美文网首页
python 编程技巧(三)

python 编程技巧(三)

作者: 你常不走的路 | 来源:发表于2018-01-06 16:42 被阅读7次

    这一篇 写一些 对 iterable 和 iterator的理解

    #首先 可迭代对象
    l = [1,2,34,56]
    s = 'abc' #这些都是可迭代对象
    #利用for 循环
    
    #而迭代器对象  就是
    iter(l)
    iter(s) 
    #利用 next  计算下一次
    

    别人总结:

    凡是可作用于for循环的对象都是Iterable类型;
    凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;

    我们介绍完了 来解决一个实例 比如 查询 天气 我们不希望等所有天气都查询完了 才显示出来
    而是希望 查询出来一个 就显示一个 这时候 我们就可以 使用这个

    import requests
    from collections import Iterable, Iterator, deque
    import pickle
    
    class WeatherIterator(Iterator):  #实现一个迭代器对象  ,next方法每次返回一个城市天气
        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 '{}: {} , {}'.format(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):  #实现一个可迭代对象,__iter__返回一个迭代器对象
        def __init__(self, cities):
            self.cities = cities
    
        def __iter__(self):
            return WeatherIterator(self.cities)  #
    
    
    city = ['北京','成都']
    for x in WeatherIterable(city):
        print(x)
    

    相关文章

      网友评论

          本文标题:python 编程技巧(三)

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