2.1【迭代器与生成器】实现可迭代对象和迭代器对象

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℃
..
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值