首页 > 编程语言 > 详细

Python迭代器

时间:2018-08-22 13:02:23      阅读:140      评论:0      收藏:0      [点我收藏+]

迭代器

 1 #生成器都是迭代器,迭代器不一定是生成器
 2 #list, tuple, dict, string:Iterable
 3 
 4 
 5 l = [1,2,3,5]
 6 
 7 d = iter(l) #生成迭代对象
 8 print(d)  #<list_iterator object at 0x7f8cf61e6a90>
 9 
10 #什么是迭代器
11 # 两个条件:1.有iter方法, 2.有next方法
12 
13 print(next(d)) # 1
14 print(next(d)) # 2
15 
16 # for 循环内部三件事
17 # 1.调用可迭代对象的iter方法返回一个迭代器对象
18 # 2.调用迭代器对象的next方法
19 # 3.处理stopIteration
20 
21 # for i in [1,2,3,4]:
22 
23 from collections import Iterable,Iterator
24 
25 print(isinstance(l,list)) #是列表
26 print(isinstance(l,Iterable)) #可迭代
27 print(isinstance(l,Iterator)) #不是迭代器
28 print(isinstance(d,Iterator)) #是迭代器

l可迭代,但不是迭代器,d是迭代器。

执行结果:

<list_iterator object at 0x7f2d5e6205f8>
1
2
True
True
False
True

Process finished with exit code 0

 

Python迭代器

原文:https://www.cnblogs.com/112358nizhipeng/p/9516911.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!