鱼C论坛

 找回密码
 立即注册
查看: 1548|回复: 0

[技术交流] 【009】Python迭代器对象减少开销

[复制链接]
发表于 2019-6-14 17:48:17 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. '''
  2. 目的:通过迭代器对象将需要信息存储到一个对象,并实时显示,减小时间和空间开销
  3. '''

  4. import requests
  5. from collections.abc import Iterator,Iterable

  6. class weatherIterator(Iterator):
  7.     def __init__(self,cities):
  8.         self.cities = cities
  9.         self.index = 0
  10.     def getweather(self,city):
  11.         r = requests.get(r'http://wthrcdn.etouch.cn/weather_mini?city='+city)
  12.         data = r.json()['data']['forecast'][0]
  13.         return '%s: %s ,%s' % (city,data['low'],data['high'])
  14.     def __next__(self):
  15.         if self.index == len(self.cities):
  16.             raise StopIteration
  17.         city = self.cities[self.index]
  18.         self.index += 1
  19.         return self.getweather(city)

  20. class weatherIterable(Iterable):
  21.     def __init__(self,cities):
  22.         self.cities = cities
  23.     def __iter__(self):
  24.         return weatherIterator(self.cities)

  25. for x in weatherIterable(['北京','上海','南京']):
  26.     print(x)
  27. '''
  28. 提问与思考:
  29. 1、for循环工作机制:可迭代对象通过调用自身的__iter__()方法生成迭代器,
  30. 迭代器对象通过__next__()方法,进行迭代访问,迭代完毕最后抛出异常StopIteration
  31. '''
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-5-10 14:34

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表