迭代器

Posted sakurayuanyuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了迭代器相关的知识,希望对你有一定的参考价值。

  • 迭代器协议:对象必须提供一个next方法,执行该方法的结束是要么返回迭代中的下一项,要么就引起一个Stoplteration异常以终止迭代(只能前进不能后退)
  • 可迭代对象:实现了迭代器协议的对象(如何实现:对象内部定义__iter__()方法)
  • 协议:一种约定,可迭代对象实现了迭代器协议,python的内部工具(如for max min sum等函数)使用迭代器协议来访问对象

 

for循环机制:

  注:字符串、列表、元组、字典、集合、文件对象,这些本不是可迭代对象,故本身没有next方法,当用for遍历这些数据类型时,会进行下列操作:

    1.调用这些数据类型中的__iter__()方法,返回值赋值给一个变量,那么这个变量就是可迭代对象

    2.依据迭代器协议,调用__next__()方法,每调用一次就会返回其中的元素,当超出元素个数后,就会报StopIteration错,但是for循环会吞并这个错误,以此来终止循环。

 

技术分享图片for 循环机制
 1 #=====================================================列表
 2 # l = [1, 2, 5]
 3 # iter = l.__iter__()    #1.用对象中的__iter__()方法来将该对象转换为可迭代对象
 4 # print(iter.__next__()) #2.调用可迭代对象中的__next__()方法
 5 # print(iter.__next__())
 6 # print(iter.__next__())
 7 # print(iter.__next__())  #StopIteration
 8 
 9 # for item in l:
10 #     print(item)
11 
12 #=====================================================字典
13 # dict = {‘name‘: ‘chen‘, ‘age‘: 13}
14 # iter = dict.__iter__() #转换为可迭代对象
15 # print(iter.__next__())
16 # print(iter.__next__())
17 # print(iter.__next__()) #StopIteration
18 
19 # for item in dict:
20 #     print(item)
21 
22 #====================================================文件对象
23 f = open(test, r, encoding=utf-8)
24 # iter = f.__iter__()
25 # print(iter.__next__(), end=‘‘)
26 # print(iter.__next__(), end=‘‘)
27 # print(iter.__next__(), end=‘‘)
28 # print(iter.__next__(), end=‘‘)
29 
30 # for item in f:
31 #     print(item, end=‘‘)

 

 

用while循环模拟for循环机制:

 

技术分享图片
1 l = [1, 2, 3]
2 iter = l.__iter__()
3 while True:
4     try:
5         print(iter.__next__())
6     except StopIteration:
7         print(循环结束了哟!)
8         break
View Code

 


以上是关于迭代器的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段6——CSS选择器

行历史查看器 - Git

持久片段和查看器

损坏的顶点和片段着色器

python使用上下文对代码片段进行计时,非装饰器

设计模式迭代器模式 ( 简介 | 适用场景 | 优缺点 | 代码示例 )