Python实现可迭代对象和迭代器对象

Jackey Python 711 次浏览 , 没有评论
# 实现可迭代对象和迭代器对象
l = [1, 2, 3, 4]
s = 'abcde'

for x in l: print(x)

for x in s: print(x)

print(iter(l))
print(iter(s))

import requests


def getWeather(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'])


#
# print(getWeather(u'北京'))
# print(getWeather(u'长春'))

from collections.abc import Iterable, Iterator


class WeatherIterator(Iterator):
    def __init__(self, cities):
        self.cities = cities
        self.index = 0

    def __next__(self):
        if self.index == len(self.cities):
            raise StopIteration
        city = self.cities[self.index]
        self.index += 1
        return self.getWeather(city)

    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'])




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)

 

发表评论

您的电子邮箱地址不会被公开。

Go