码迷,mamicode.com
首页 > 编程语言 > 详细

python3 迭代器

时间:2017-06-19 20:56:25      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:obj   回退   size   lis   pre   family   ros   font   while   

一 、什么是迭代
1、 重复
2、下次重复一定是基于上一次的结果而来


while True:
cmd=input(‘:‘)
print(cmd)


l=[1,2,3,4]
count=0
while count < len(l):
print(l[count])
count+=1


二、 可迭代对象:obj.__iter__

三 、迭代器:iter1=obj.__iter__()
1 iter1.__next__
2 iter1.__iter__

iter1.__next__()
iter1.__next__()
iter1.__next__()

迭代器:
优点:
1 不依赖索引
2 惰性计算,节省内存

缺点:
1 不如按照索引的取值方便
2 一次性,只能往后取,不能回退
l=[1,2,3]
for i in l: # obj=l.__iter__()
print(i)



迭代器的应用:
1、提供了一种不依赖索引的统一的迭代方法
2、 惰性计算,比如取文件的每一行



list = [1,2,3,4,5]
i = iter(list) #迭代器函数
print(i.__next__())
print(i.__next__())
print(i.__next__())
print(i.__next__())
print(i.__next__())


i = list.__iter__() #迭代器对象
i.__next__()

s1=‘hello‘
s1.__iter__()
l=[1,2,3]
l.__iter__()
t=(1,2,3)
t.__iter__()
set1={1,2,3}
set1.__iter__()
d={‘a‘:1,‘b‘:2,‘c‘:3}
d.__iter__()


f=open(‘db.txt‘,encoding=‘utf-8‘)
print(f.__next__())

python3 迭代器

标签:obj   回退   size   lis   pre   family   ros   font   while   

原文地址:http://www.cnblogs.com/lucaq/p/7050379.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!