列表和字符串都是可迭代對象侦讨。
for x in list: print(x)
for x in string: print(x)
# list 和 string 都是可迭代對象
可迭代對象具有
__iter__
方法或者__getitem__
方法薄扁。
迭代器對象具有next()
或者__next__()
方法。
iter(iterable_object)
將可迭代對象 iterable_object
轉(zhuǎn)化為了一個迭代器對象集嵌。
# 一個獲取天氣的小程序女仰,先創(chuàng)建一個WeatherIterator對象,再創(chuàng)建一個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℃