列表和字符串都是可迭代对象。
for x in list: print(x)
for x in string: print(x)
# list 和 string 都是可迭代对象
可迭代对象具有
__iter__
方法或者__getitem__
方法。
迭代器对象具有next()
或者__next__()
方法。
iter(iterable_object)
将可迭代对象 iterable_object
转化为了一个迭代器对象。
# 一个获取天气的小程序,先创建一个WeatherIterator对象,再创建一个WeaTherIterable对象
import requests
from collections import Iterable, Iterator
class WeatherIterator(Iterator):
def __init__(self, cities):
self.cities = cities
self.index = 0
def get_weather(self, city):
r = requests.get("http://wthrcdn.etouch.cn/weather_mini?city=" + city)
data = r.json()['data']['forecast'][0]
return '{0}, {1}, {2}'.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.get_weather(city)
class WeatherIterable(Iterable):
def __init__(self, cities):
self.cities = cities
def __iter__(self):
return WeatherIterator(self.cities)
for x in WeatherIterable(['北京', '上海', '广州']):
print(x)
# 输出为:
# 北京, 低温 15℃, 高温 26℃
# 上海, 低温 18℃, 高温 21℃
# 广州, 低温 22℃, 高温 27℃