自己公司设计一个网站,学校网站建设介绍,jsp手机销售网站的建设,室内设计软件课程文章目录 [toc]什么是迭代可迭代对象判断数据类型是否是可迭代类型 迭代器对可迭代对象进行迭代的本质获取可迭代对象的迭代器通过迭代器获取数据StopIteration异常 自定义迭代器__iter__()方法__next__()方法判断数据类型是否是可迭代类型自定义迭代器案例分离模式整合模式 fo… 文章目录 [toc]什么是迭代可迭代对象判断数据类型是否是可迭代类型 迭代器对可迭代对象进行迭代的本质获取可迭代对象的迭代器通过迭代器获取数据StopIteration异常 自定义迭代器__iter__()方法__next__()方法判断数据类型是否是可迭代类型自定义迭代器案例分离模式整合模式 for循环的本质 接收可迭代对象的方式示例
什么是迭代
迭代是访问序列类型元素的一种方式
nums [1, 2, 3, 4, 5, 6]for num in nums:print(num)1
2
3
4
5
6可以使用for循环对string、list、tuple、dict、set等数据类型进行遍历从中依次获取元素这个过程称为迭代 可迭代对象
是否所有的数据类型都可以通过for循环进行迭代呢
tel 10086for item in tel:print(item)Traceback (most recent call last):File C:/Users/FOLLOW_MY_HEART/Desktop/Python基础/【Python基础】迭代器/test.py, line 3, in modulefor item in tel:
TypeError: int object is not iterable通过运行发现TypeError异常显示int类型不是iterable类型即可迭代类型
判断数据类型是否是可迭代类型
from collections.abc import Iterable# 判断 string 类型是否是可迭代类型
print(isinstance(abcdef, Iterable))
# 判断 list 类型是否是可迭代类型
print(isinstance([], Iterable))
# 判断 tuple 类型是否是可迭代类型
print(isinstance((0, 0), Iterable))
# 判断 dict 类型是否是可迭代类型
print(isinstance({key: value}, Iterable))
# 判断 set 类型是否是可迭代类型
print(isinstance({}, Iterable))# 判断 int 类型是否是可迭代类型
print(isinstance(0, Iterable))
# 判断 float 类型是否是可迭代类型
print(isinstance(3.14, Iterable))True
True
True
True
True
False
False可以看到string、list、tuple、dict、set数据类型是Iterable类的实例是可迭代类型int、float数据类型不是Iterable类的实例不是可迭代类型 迭代器
迭代器是一个记录遍历位置的对象迭代器对象从第一个元素开始访问直至对所有的元素进行了访问迭代器只能前进不能后退
对可迭代对象进行迭代的本质 在对可迭代对象进行迭代的过程中每迭代一步都会返回对象的下一个元素数据一直向后读取元素数据直至迭代了所有的元素 在这个过程中应该存在记录当前遍历位置的对象以便每一步迭代都能返回下一条数据这个对象就是迭代器 可迭代对象的本质就是提供了进行数据迭代的迭代器对象的对象类型 list、tuple等都是可迭代对象可以通过iter()函数获取这些可迭代对象提供的迭代器然后可以通过对迭代器使用next()函数来获取下一条数据
获取可迭代对象的迭代器
通过iter()函数获取可迭代对象的迭代器
from collections.abc import Iteratornums [1, 2, 3, 4, 5, 6]nums_iter iter(nums) # 获取 list 对象的迭代器print(type(nums_iter))print(isinstance(nums, Iterator))
print(isinstance(nums_iter, Iterator))class list_iterator
False
True通过迭代器获取数据
通过对迭代器使用next()函数来获取下一条数据
nums [1, 2, 3]nums_iter iter(nums) # 获取 list 对象的迭代器num1 next(nums_iter)
print(num1)num2 next(nums_iter)
print(num2)num3 next(nums_iter)
print(num3)1
2
3StopIteration异常
如果将上面的代码多调用一次next()会发生什么
nums [1, 2, 3]nums_iter iter(nums) # 获取 list 对象的迭代器num1 next(nums_iter)
print(num1)num2 next(nums_iter)
print(num2)num3 next(nums_iter)
print(num3)num4 next(nums_iter) # 这里会产生异常
print(num4)1
2
3
Traceback (most recent call last):File C:/Users/FOLLOW_MY_HEART/Desktop/Python基础/【Python基础】迭代器/test.py, line 14, in modulenum4 next(nums_iter)
StopIteration可以看到第 14 14 14行代码处产生了异常因为列表nums中只有 3 3 3个元素调用 4 4 4次next()显然无法获取到第 4 4 4个元素所以StopIteration异常其实是一种告知迭代结束的标志而已添加异常处理即可解决问题
nums [1, 2, 3]nums_iter iter(nums) # 获取 list 对象的迭代器num1 next(nums_iter)
print(num1)num2 next(nums_iter)
print(num2)num3 next(nums_iter)
print(num3)try:num4 next(nums_iter)print(num4)
except StopIteration as e:print(迭代结束)1
2
3
迭代结束自定义迭代器
上面提到的iter()方法必须是对可迭代对象才能提取到迭代器对象但是怎样保证自定义对象是可迭代对象呢
__iter__()方法
无__iter__()方法
from collections.abc import Iterableclass MyList:def __init__(self):self.my_list list()def add(self, item):self.my_list.append(item)mylist MyList()print(isinstance(mylist, Iterable))False有__iter__()方法
from collections.abc import Iterableclass MyList:def __init__(self):self.my_list list()def add(self, item):self.my_list.append(item)def __iter__(self):passmylist MyList()print(isinstance(mylist, Iterable))True可以看出只要一个类定义了__iter__()方法那么这个类的实例就是可迭代对象实际上当调用iter()方法获取一个可迭代对象的迭代器时会自动触发这个对象的__iter__()方法返回这个对象的迭代器
__next__()方法
通过对迭代器使用next()函数能够获取下一条数据实际上会自动触发这个对象的__next__()方法所以想要构造一个迭代器就要实现__next__()方法Python要求迭代器本身也是可迭代的所以还要为迭代器类实现__iter__()方法而__iter__()方法要返回一个迭代器迭代器自身正是一个迭代器所以迭代器类的__iter__()方法返回自身即可一个实现了__iter__()方法和__next__()方法的对象就是迭代器
判断数据类型是否是可迭代类型
使用isinstance()判断一个对象是否是Iterator对象
from collections.abc import Iterable, Iteratornums [1, 2, 3]print(isinstance(nums, Iterable))
print(isinstance(nums, Iterator))nums_iter iter(nums) # 获取 list 对象的迭代器print(isinstance(nums_iter, Iterable))
print(isinstance(nums_iter, Iterator))True
False
True
True自定义迭代器案例
分离模式
class MyList:def __init__(self):self.items list()self.current 0 # 记录当前迭代位置def add(self, value):self.items.append(value)def __iter__(self):return MyIterator(self) # 返回一个迭代器对象class MyIterator:def __init__(self, my_list_obj):self.my_list_obj my_list_objdef __iter__(self):return selfdef __next__(self):if self.my_list_obj.current len(self.my_list_obj.items):item self.my_list_obj.items[self.my_list_obj.current]self.my_list_obj.current 1 # 当前迭代位置加 1return itemelse:raise StopIteration # 手动抛出异常if __name__ __main__:my_list MyList()my_list.add(1)my_list.add(2)my_list.add(3)iter_obj iter(my_list)print(next(iter_obj)) # 打印 1# 打印 2、3, 思考一下为什么 for 循环从 2 开始打印for item in my_list:print(item)1
2
3整合模式
class MyList:def __init__(self):self.items list()self.current 0 # 记录当前迭代位置def add(self, value):self.items.append(value)def __iter__(self):return self # 返回一个迭代器对象def __next__(self):if self.current len(self.items):item self.items[self.current]self.current 1 # 当前迭代位置加 1return itemelse:raise StopIteration # 手动抛出异常if __name__ __main__:my_list MyList()my_list.add(1)my_list.add(2)my_list.add(3)iter_obj iter(my_list)print(next(iter_obj)) # 打印 1# 打印 2、3, 思考一下为什么 for 循环从 2 开始打印for item in my_list:print(item)for循环的本质
nums [1, 2, 3, 4, 5, 6]nums_iter iter(nums)
while True:try:print(next(nums_iter))except StopIteration:break1
2
3
4
5
6在对可迭代对象进行迭代时for循环先调用iter()方法会自动触发这个对象的__iter__()方法返回这个对象的迭代器然后对获取到的迭代器不断调用next()方法会自动触发这个对象的__next__()方法返回下一条数据最后通过处理StopIteration异常来结束循环 接收可迭代对象的方式
并不是只有for循环能够接收可迭代对象list()、tuple()等也能接收可迭代对象
示例
class MyList:def __init__(self):self.items list()self.current 0 # 记录当前迭代位置def add(self, value):self.items.append(value)def __iter__(self):return self # 返回一个迭代器对象def __next__(self):if self.current len(self.items):item self.items[self.current]self.current 1 # 当前迭代位置加 1return itemelse:raise StopIteration # 手动抛出异常if __name__ __main__:my_list MyList()my_list.add(1)my_list.add(2)my_list.add(3)iter_obj iter(my_list)print(list(iter_obj))[1, 2, 3]对迭代器iter_obj调用list()返回了包含迭代出的所有数据的列表
文章转载自: http://www.morning.gcrlb.cn.gov.cn.gcrlb.cn http://www.morning.touziyou.cn.gov.cn.touziyou.cn http://www.morning.ltywr.cn.gov.cn.ltywr.cn http://www.morning.xnpml.cn.gov.cn.xnpml.cn http://www.morning.gychx.cn.gov.cn.gychx.cn http://www.morning.rbgwj.cn.gov.cn.rbgwj.cn http://www.morning.mtrfz.cn.gov.cn.mtrfz.cn http://www.morning.jzdfc.cn.gov.cn.jzdfc.cn http://www.morning.dwztj.cn.gov.cn.dwztj.cn http://www.morning.sxwfx.cn.gov.cn.sxwfx.cn http://www.morning.hsklc.cn.gov.cn.hsklc.cn http://www.morning.tcpnp.cn.gov.cn.tcpnp.cn http://www.morning.kynf.cn.gov.cn.kynf.cn http://www.morning.ncfky.cn.gov.cn.ncfky.cn http://www.morning.ggjlm.cn.gov.cn.ggjlm.cn http://www.morning.rdlrm.cn.gov.cn.rdlrm.cn http://www.morning.ycwym.cn.gov.cn.ycwym.cn http://www.morning.kjgrg.cn.gov.cn.kjgrg.cn http://www.morning.qhqgk.cn.gov.cn.qhqgk.cn http://www.morning.pghry.cn.gov.cn.pghry.cn http://www.morning.drggr.cn.gov.cn.drggr.cn http://www.morning.zcnwg.cn.gov.cn.zcnwg.cn http://www.morning.yjtnc.cn.gov.cn.yjtnc.cn http://www.morning.lkpzx.cn.gov.cn.lkpzx.cn http://www.morning.wrbf.cn.gov.cn.wrbf.cn http://www.morning.ngcw.cn.gov.cn.ngcw.cn http://www.morning.hrkth.cn.gov.cn.hrkth.cn http://www.morning.qrlsy.cn.gov.cn.qrlsy.cn http://www.morning.mnqg.cn.gov.cn.mnqg.cn http://www.morning.xdjsx.cn.gov.cn.xdjsx.cn http://www.morning.jfgmx.cn.gov.cn.jfgmx.cn http://www.morning.wbxbj.cn.gov.cn.wbxbj.cn http://www.morning.bojkosvit.com.gov.cn.bojkosvit.com http://www.morning.lqljj.cn.gov.cn.lqljj.cn http://www.morning.fhqsm.cn.gov.cn.fhqsm.cn http://www.morning.hqrkq.cn.gov.cn.hqrkq.cn http://www.morning.czcbl.cn.gov.cn.czcbl.cn http://www.morning.gjlst.cn.gov.cn.gjlst.cn http://www.morning.vehna.com.gov.cn.vehna.com http://www.morning.huxinzuche.cn.gov.cn.huxinzuche.cn http://www.morning.ptqds.cn.gov.cn.ptqds.cn http://www.morning.qprtm.cn.gov.cn.qprtm.cn http://www.morning.qzxb.cn.gov.cn.qzxb.cn http://www.morning.trnhy.cn.gov.cn.trnhy.cn http://www.morning.lffrh.cn.gov.cn.lffrh.cn http://www.morning.tsyny.cn.gov.cn.tsyny.cn http://www.morning.dfmjm.cn.gov.cn.dfmjm.cn http://www.morning.wtnwf.cn.gov.cn.wtnwf.cn http://www.morning.mxnfh.cn.gov.cn.mxnfh.cn http://www.morning.hwnnm.cn.gov.cn.hwnnm.cn http://www.morning.ksgjy.cn.gov.cn.ksgjy.cn http://www.morning.ggnrt.cn.gov.cn.ggnrt.cn http://www.morning.tfsyk.cn.gov.cn.tfsyk.cn http://www.morning.fpxms.cn.gov.cn.fpxms.cn http://www.morning.rkbly.cn.gov.cn.rkbly.cn http://www.morning.rgmd.cn.gov.cn.rgmd.cn http://www.morning.kpbgvaf.cn.gov.cn.kpbgvaf.cn http://www.morning.yngtl.cn.gov.cn.yngtl.cn http://www.morning.xsqbx.cn.gov.cn.xsqbx.cn http://www.morning.jcfg.cn.gov.cn.jcfg.cn http://www.morning.yqndr.cn.gov.cn.yqndr.cn http://www.morning.knnhd.cn.gov.cn.knnhd.cn http://www.morning.crrmg.cn.gov.cn.crrmg.cn http://www.morning.sdhmn.cn.gov.cn.sdhmn.cn http://www.morning.0dirty.cn.gov.cn.0dirty.cn http://www.morning.hdnd.cn.gov.cn.hdnd.cn http://www.morning.jjxxm.cn.gov.cn.jjxxm.cn http://www.morning.hcxhz.cn.gov.cn.hcxhz.cn http://www.morning.gnwse.com.gov.cn.gnwse.com http://www.morning.fpngg.cn.gov.cn.fpngg.cn http://www.morning.wkwds.cn.gov.cn.wkwds.cn http://www.morning.rmxk.cn.gov.cn.rmxk.cn http://www.morning.swkpq.cn.gov.cn.swkpq.cn http://www.morning.xinxianzhi005.com.gov.cn.xinxianzhi005.com http://www.morning.muniubangcaishui.cn.gov.cn.muniubangcaishui.cn http://www.morning.hdlhh.cn.gov.cn.hdlhh.cn http://www.morning.ydhck.cn.gov.cn.ydhck.cn http://www.morning.pgggs.cn.gov.cn.pgggs.cn http://www.morning.btjyp.cn.gov.cn.btjyp.cn http://www.morning.dmlgq.cn.gov.cn.dmlgq.cn