8.python3实用编程技巧进阶(三)
程序员文章站
2022-10-04 11:26:35
3.1.如何实现可迭代对象和迭代器对象 结果 3.2如何使用生成器函数实现可迭代对象 3.3.如何进行反向迭代以及如何实现反向迭代 反向迭代 要想实现反向迭代必须实现__reversed__方法 ......
3.1.如何实现可迭代对象和迭代器对象
#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如何使用生成器函数实现可迭代对象
#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)
3.3.如何进行反向迭代以及如何实现反向迭代
反向迭代
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)
上一篇: Android中四种补间动画的使用示例(附代码下载)
下一篇: 如何用Python实现敏感词的过滤