python3 迭代器与生成器

迭代器

使用迭代器可以很方便地进行for循环获取对象中的数据
实现__iter__()、__next__()方法,用于返回迭代的对象和元素。iter()可以将可迭代对象转换为迭代器
反向迭代器需要实现__reversed__()接口

使用for循环迭代天气类,获取城市列表中的天气信息

import requests


class Weather:
    def __init__(self, cities_name):
        self.cities_name = cities_name
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        size = len(self.cities_name)
        if self.index == size:
            raise StopIteration
        else:
            city_name = self.cities_name[self.index]
            self.index += 1
            return self.get_weather(city_name)

    def get_weather(self, city_name):
        url = 'http://wthrcdn.etouch.cn/weather_mini?city={}'.format(city_name)
        r = requests.get(url).json()
        if r['desc'] != 'OK':
            return r['desc']
        else:
            return '{}{}{}'.format(city_name, format(r['data']['forecast'][0]['high'], '^10'),
                                   format(r['data']['forecast'][0]['low'], '^10'))


if __name__ == '__main__':
    for w in Weather(['北京', '上海', '武汉', '九江', '江西']):
        print(w)

run
北京 高温 18℃ 低温 8℃
上海 高温 20℃ 低温 13℃
武汉 高温 22℃ 低温 12℃
九江 高温 21℃ 低温 12℃
invilad-citykey

反向迭代器

class FloatRange:
    def __init__(self, start, end, step=0.1):
        self.start = start
        self.end = end
        self.step = step

    def __iter__(self):
        res = self.start
        while res <= self.end:
            yield res
            res += self.step

    def __reversed__(self):
        """
        反向迭代器的接口
        :return:
        """
        res = self.end
        while res >= self.start:
            yield res
            res -= self.step


fr = FloatRange(1.0, 5.0, 0.5)
for e in fr:
    print('{:.2f}'.format(e), end=' ')
print()


for e in reversed(fr):
    print('{:.2f}'.format(e), end=' ')
print()

生成器

带有yield的函数被认为是生成器函数,将会被解释成可迭代器对象。程序执行到yield的时候将会被暂停,再次被迭代的时候,将会从上次执行的位置继续



def fib(max_val):
    a, b = 0, 1
    while a < max_val:
        yield a  # 函数执行这里之后,将会暂时停止,返回a, 并等待下一次的迭代
        a, b = b, a + b


if __name__ == "__main__":
    for e in fib(100):  # 迭代生成器对象
        print(e, end=" ")
    print()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章