a = [1,2,3,4]
b = 'abcde'
for x in a:print x
for x in b:print x
#a,b为可迭代对象
iter(a)# 迭代器对象
a.__
a.__iter__ # 可迭代接口
iter(a) 实际调用了 a.__iter__()
b.__
b.__getitem__# sequence序列的接口
t = iter(a) # 迭代器对象
t.next()# 可迭代接口
1
t.next()
2
t.next()
3
t.next()
4
t.next()
抛出异常
for x in a: print x#调用.nxet(),直到捕获StopIteration异常,跳出循环
可迭代对象、迭代器对象
from collections import Iterable,Iterator
抽象接口
Iterable.__abstractmethods__
frozenset({'__iter__'})
Iterator.__abstractmethods__
frozenset({'next'})
#
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'北京')
#
惰性获取,并能封装到一个对象中,可用for迭代
实现一个迭代器对象WeatherItorator, next方法每次返回一个数据
实现一个可迭代对象WeatherItorable, __iter__方法返回一个迭代器对象
#Iterator的计算是惰性的,只有在需要返回下一个数据时它才会计算
from collections import Iterable,Iterator
class WeatherIterator(Iterator):
# 定义构造器
def __init__(self,cities):
self.cities = cities
self.index = 0
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'])
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)
for x in WeatherIterable([u'北京',u'上海',u'广州',u'深圳']):
print x
#北京:低温 20℃,高温 31℃
#上海:低温 20℃,高温 26℃
..
2.1【迭代器与生成器】实现可迭代对象和迭代器对象
于 2023-04-10 10:35:04 首次发布
文章讲述了Python编程中迭代器和可迭代对象的概念,包括如何创建和使用它们。通过示例展示了如何利用`requests`库获取天气信息,并设计了一个惰性的WeatherIterator类,该类在需要时计算下一个城市的天气数据,支持通过for循环迭代多个城市天气。
摘要由CSDN通过智能技术生成