1、打开Python开发工具IDLE,新建‘iter.py’文件,编写代码如下:from collections.abc import Iterablelist1 = [x for x in range(5)]print (isinstance(list1,Iterable))
2、F5运行程序,列表属于可迭代对象,isinstance方法判断为true
3、列表转换为迭代器,代码如下:from collections.abc import Iterablelist1 = [x for x in range(5)]print (isinstance(list1,Iterable))ilist = iter(list1)print (type(ilist))
4、F5运行程序,列表转换成迭代器
5、迭代器有next方法,代码如下:from collections.abc import Iterablelist1 = [x for x in range(5)]print (isinstance(list1,Iterable))ilist = iter(list1)print (type(ilist))print (next(ilist))print (ilist.__next__())
6、F5运行程序,next执行,迭代器读取内容
7、for循环遍历相当于最后捕捉了迭代器最后一个next方法的异常,代码如下:from collections.abc import Iterablelist1 = [x for x in range(5)]print (isinstance(list1,Iterable))ilist = iter(list1)print (type(ilist))print (next(ilist))print (ilist.__next__())while 1: try: print (next(ilist)) except StopIteration: break
8、F5运行程序,迭代器取完内容,异常被捕获,while循环结束