zoukankan      html  css  js  c++  java
  • 可迭代对象和迭代器生成器

    """
    iter(...)
        iter(iterable) -> iterator
        iter(callable, sentinel) -> iterator
    
        Get an iterator from an object.  In the first form, the argument must
        supply its own iterator, or be a sequence.
        In the second form, the callable is called until it returns the sentinel.
    """
    
    # 可以由可迭代对象得到一个迭代器
    l = [1,2,3,4]
    print(iter(l)) # <list_iterator object at 0x000002D7D2D7B208>
    print(l.__iter__()) # <list_iterator object at 0x000001E6BE719198>
    
    """
    可迭代对象满足了迭代协议的一个接口 __iter__ 或者 __getitem__
    迭代器对象只有一个接口__next__
    next 可以得到迭代器中的下一个元素,最后一个元素被取出后,会抛出StopIteration异常
    
    for循环工作机制:
    1.由iter方法得到一个迭代器
    2.不停地调用next方法,直到捕获一个会抛出StopIteration异常,退出循环
    
    """
    
    
    """
    如何实现可迭代对象和迭代器对象
    
    实际案例:
    某软件要求,从网络抓取各个城市的气温信息,并以此显示:
    北京:15-20
    天津:17-22
    长春:12-18
    ....
    
    
    如果一次抓取所有的城市天气再显示,显示第一个城市气温时,有很高的延时,并且浪费存储空间。
    我们期望以“用时访问”策略,并且能把所有的城市气温封装到一个对象里,可用for语句进行迭代,如何解决?
    
    解决方案:
    1.实现一个迭代器对象WeatherIterator,next方法每次返回一个气温
    2.实现一个可迭代对象WeatherIterable,__iter__方法返回一个迭代器对象
    
    """
    
    
    import requests
    from collections import Iterable,Iterator
    
    class WeatherIterator(Iterator):
        """
        迭代器对象,满足__next__接口
        """
        def __init__(self,citys):
            self.citys = citys
            self.index = 0
    
        def _getCityWeather(self,city):
            r = requests.get("http://wthrcdn.etouch.cn/weather_mini?city=%s" % city)
            data = r.json()['data']['forecast'][0]
            return "%s:%s-%s" % (city, data['low'], data['high'])
    
        def __next__(self):
            if self.index == len(self.citys):
                raise StopIteration
            city = self.citys[self.index]
            self.index += 1
            return self._getCityWeather(city)
    
    class WeatherIterable(Iterable):
        """
        可迭代对象,满足__iter__接口
        """
        def __init__(self,citys):
            self.citys = citys
    
        def __iter__(self):
            return WeatherIterator(self.citys)
    
    citys = ['北京', '上海', '广州', '深圳']
    weather_obj = WeatherIterable(citys)
    
    for x in weather_obj:
        print(x)
  • 相关阅读:
    源码
    Leetcode 230. 二叉搜索树中第K小的元素 中序遍历
    Leetcode 160. 相交链表 哈希 链表
    Leetcode 142. 环形链表 II
    Leetcode 217. 存在重复元素 哈希 排序
    asp.mvc2.0资料
    关于CRM的介绍
    WPf控件模板缺省样式
    皮肤制作工具
    关于linq的用法
  • 原文地址:https://www.cnblogs.com/haiyan123/p/7987129.html
Copyright © 2011-2022 走看看