8、如何实现可迭代对象和迭代器对象 9、如何使用生成器函数实现可迭代对象 10、如何进行反向迭代以及如何实现反向迭代 11、如何对迭代器做切片操作 12、如何在一个for语句中迭代多个可迭代对象
8、如何实现可迭代对象和迭代器对象
PS:注意重载Iterator方法的时候,需要和原来的方法名一样,否则创建实例时会报错
from collections import Iterator,Iterable import requests,json class WeatherItertor(Iterator): def __init__(self,city_list): self.CityList = city_list self.indexA = 0 def getWeather(self,city): r = requests.get('http://www.weather.com.cn/data/sk/{code}.html'.format(code=city)) ret = json.loads(r.content.decode("utf-8")) #风向 WD = ret["weatherinfo"]["WD"] #城市 city_data = ret["weatherinfo"]["city"] return "城市:{city},风向:{WD}".format(city=city_data,WD=WD) def __next__(self): if self.indexA == len(self.CityList): raise StopIteration city = self.CityList[self.indexA] self.indexA += 1 return self.getWeather(city) class WeatherIterable(Iterable): def __init__(self,city_list): self.CityList =city_list def __iter__(self): return WeatherItertor(self.CityList) # citys = {'北京':101010100,'朝阳':101010300,'顺义':101010400,'怀柔':101010500} citys_list = [101010100,101010300,101010400,101010500] ret = WeatherIterable(citys_list) for x in ret: print(x)
result:
C:\Python35-32\python.exe C:/laoni/PycharmProjects/TEXT/aa.py
城市:北京,风向:东南风
城市:朝阳,风向:南风
城市:顺义,风向:南风
城市:怀柔,风向:西南风
9、如何使用生成器函数实现可迭代对象
函数里有yield关键是,则是生成器,生成器内置有__iter__方法,只不过调用__iter__返回的是生成器本身,利用这一特性,可以创建一个可迭代对象的类。
class PrimeNum(): def __init__(self,start,end): self.start = start self.end = end def aa_bb(self,x): if x % 2 ==0: ret = "这是一个偶数:{info}".format(info=x) elif x % 2 !=0: ret = "这是一个奇数:{info}".format(info=x) else: pass return ret def __iter__(self): for x in range(self.start,self.end): p = self.aa_bb(x) yield p for x in PrimeNum(1,8): print(x) result: 这是一个奇数:1 这是一个偶数:2 这是一个奇数:3 这是一个偶数:4 这是一个奇数:5 这是一个偶数:6 这是一个奇数:7
10、如何进行反向迭代以及如何实现反向迭代
正向的可以使用iter函数获取正向的迭代器,reversed函数可以获取反向的迭代器,使用reversed的前提是对象本身具有__reversed__方法
class FloatRange(): def __init__(self,start,end,step=0.2): self.start =start self.end = end self.step = step def __iter__(self): t = self.start while t <= self.end: yield t t += self.step def __reversed__(self): t = self.end while t >= self.start: yield t t -= self.step for x in reversed(FloatRange(1,4)): print(x) 结果: 4 3.8 3.5999999999999996 3.3999999999999995 3.1999999999999993 2.999999999999999 2.799999999999999 2.5999999999999988 2.3999999999999986 2.1999999999999984 1.9999999999999984 1.7999999999999985 1.5999999999999985 1.3999999999999986 1.1999999999999986
11、如何对迭代器做切片操作
通过readlines方法可以获取到,
f = open('H2','r') print(f) ret = f.readlines() print(ret[1:3]) result: <_io.TextIOWrapper name='H2' mode='r' encoding='cp936'> [' log 127.0.0.1 local2\n', ' daemon\n']
使用itertools.islice
from itertools import islice f = open('H2','r') #获取第10到第20行 info = islice(f,10,20) print(info) for x in info: print(x) #获取开始到第二十行 info2 = islice(f,30) #获取第四十行到结尾 info3 = islice(f,40,None) retsult: <itertools.islice object at 0x01803F00> timeout server 50000ms option dontlognull listen scats :8888 stats enable stats uri /admin stats auth admin:1234 frontend oldboy.org bind 0.0.0.0:80 option httplog
12、如何在一个for语句中迭代多个可迭代对象
from random import randint from itertools import chain #并行 Chinese = [randint(40,100) for x in range(10)] Math = [randint(50,100) for x in range(10)] English = [randint(60,100) for x in range(10)] print(Chinese,Math,English) result = [] for C,M,E in zip(Chinese,Math,English): ret = C + M + E result.append(ret) print(result) #串行 class_one = [randint(40,100) for x in range(6)] class_two = [randint(50,100) for x in range(8)] class_three = [randint(60,100) for x in range(9)] chin = 0 for x in chain(class_one,class_two,class_three): if x >= 90: chin += 1 print(chin)