迭代器_学习笔记

 1 # Author:CallMeV
 2 # DATE  :2019-11-10
 3 # Time  : 10:43
 4 
 5 # 迭代器的创建
 6 l = [1,2,3,4]
 7 d = iter(l) # <list_iterator object at 0x000002AEA4DD4490>
 8 print(d)
 9 print(next(d))
10 print(next(d))
11 print(next(d))
12 print(next(d))
13 
14 
15 # for循环做的三件事情:
16 #     1、调用iter方法返回一个可迭代对象
17 #     2、不断调用可迭代对象的next方法
18 #     3、处理StopInteration
19 for i in [1,2,3,4]:
20     print(i)
21 
22 from collections import Iterator
23 print(isinstance([1,2],list))
24 print(isinstance(l,Iterator))
25 print(isinstance(d,Iterator))

迭代器满足两个条件:1 有 iter 方法    2 有 next 方法

猜你喜欢

转载自www.cnblogs.com/fly10086/p/11829270.html