发布于2019-08-17 14:46 阅读(1086) 评论(0) 点赞(1) 收藏(2)
#3.1 如何实现可迭代对象和迭代器对象 import requests from collections.abc import Iterable,Iterator class WeatherIterator(Iterator): def __init__(self,cities): self.cities = cities #从列表中迭代一个city,index就+1 self.index = 0 def __next__(self): #如果所有的城市都迭代完了,就抛出异常 if self.index == len(self.cities): raise StopIteration #当前迭代的city city = self.cities[self.index] #迭代完当前city,index就+1 self.index += 1 return self.get_weather(city) def get_weather(self,city): url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + city r = requests.get(url) #获取当天的天气信息 data = r.json()['data']['forecast'][0] #返回城市名字、最高和最低气温 return city, data['high'], data['low'] class WeatherIterable(Iterable): def __init__(self,cities): self.cities = cities def __iter__(self): return WeatherIterator(self.cities) def show(w): for x in w: print(x) weather = WeatherIterable(['北京','上海','广州','深圳','东莞']) show(weather)
结果
#3.2如何使用生成器函数实现可迭代对象 from collections.abc import Iterable class PrimeNumbers(Iterable): def __init__(self,a,b): self.a = a self.b = b def __iter__(self): for k in range(self.a,self.b): if self.is_prime(k): yield k def is_prime(self,k): return False if k < 2 else all(map(lambda x : k % x, range(2, k))) #打印1到30直接的素数 pn = PrimeNumbers(1, 30) for n in pn: print(n)
反向迭代
In [75]: l = [1,2,3,4,5] In [76]: for x in l: ...: print(x) ...: 1 2 3 4 5 In [77]: for x in reversed(l): ...: print(x) ...: 5 4 3 2 1
要想实现反向迭代必须实现__reversed__方法
#3.3.如何进行反向迭代以及如何实现反向迭代 class IntRange: def __init__(self,a,b,step): self.a = a self.b = b self.step = step def __iter__(self): t = self.a while t <= self.b: yield t t += self.step def __reversed__(self): t = self.b while t >= self.a: yield t t -= self.step fr = IntRange(1, 10, 2) for x in fr: print(x) print('=' * 30) #反向迭代 for y in reversed(fr): print(y)
作者:集天地之正气
链接:https://www.pythonheidong.com/blog/article/47434/bfdd649ea4fb62ac77c7/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!