python-迭代器

迭代器和可迭代对象

本日记使用Python3版本
1
2
3
4
5
6
7
# 通过可迭代对象获取迭代器

# 可迭代对象 a
a = [1,2,3,4]

# 迭代器 b
b = iter(a)
1
b
<list_iterator at 0x7f3bf8317630>
1
2
# 而迭代器__next__()方法 直到捕获停止迭代异常
b.__next__()
1

构造一个关于天气的可迭代对象

1
2
3
4
5
6
7
8
import requests

def getWeather(city):
r = requests.get('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('桂林'))
桂林: 低温 8℃, 高温 13℃
1
from collections import Iterable, Iterator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 天气的迭代器
class WeatherIterator(Iterator):
def __init__(self, cities):
self.cities = cities
self.index = 0

def getWeather(self, city):
r = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=' + city)
data = r.json()['data']['forecast'][0]
return '%s: %s, %s' % (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.getWeather(city)


# 天气的可迭代对象
class WeatherIterable(Iterable):
def __init__(self, cities):
self.cities = cities

def __iter__(self):
return WeatherIterator(self.cities)
1
2
for x in WeatherIterable(['天津', '桂林', '北海']):
print(x)
天津: 低温 0℃, 高温 5℃
桂林: 低温 8℃, 高温 13℃
北海: 低温 24℃, 高温 28℃
1
WeatherIterator(['南宁']).__next__()
'南宁: 低温 17℃, 高温 21℃'
总结
实现一个可迭代的类以及类的可迭代对象,需要重写其关键的__init__,__next__,__iter__方法