Fork me on GitHub
# 什么是迭代?指的是一个重复的过程,每一次重复称为一次迭代,并且每一次重复的结果都是下一次重复的初始值
# l=['a','b','c']
# count=0
# while count < len(l):
# print(l[count])
# count += 1
'''
a
b
c
'''
# 为什么要有迭代器?
# 对于序列类型:str list tuple,可以依赖索引来迭代取值,但是对于dict set 文件,python必须为我们提供一种不依赖于索引的迭代取值方式,

# 可迭代对象:obj.__iter__ 字符串 列表 元组 字典
# name='Rambo'
# l=[1,2,3]
# t=(1,2,3)
# d={'name':'Rambo','age':18,'gender':'male'}
# s={'a','b','c'}
# f=open('a.txt','w',encoding='utf-8')

# name.__iter__
# t.__iter__()
# l.__iter__()
# d.__iter__()
# s.__iter__()
# f.__iter__()

# 迭代器对象:obj.__iter__ obj.__next__
# f.__next__()

# 总结:
# 可迭代对象不一定是迭代器对象
# 迭代器对象一定是可迭代对象

# 调用obj.__iter__()得到的是迭代器对象
# name='Rambo'
# d_iter=name.__iter__()
# d_iter.__next__()

# 对于迭代器对象,执行obj.__iter__(),得到的还是它本身
# f=open('a.txt','w',encoding='utf-8')
# f_iter=f.__iter__().__iter__()
# f_iter.__iter__()
# f_iter.__next__()

# f=open('a.txt','w',encoding='utf-8')
# f_iter=f.__iter__()
# print(f_iter is f) # True

# d={'name':'Rambo','age':18,'gender':'male'}
# d_dit=d.__iter__()
# print(d_dit.__next__()) # name
# print(d_dit.__next__())
# print(d_dit.__next__())
'''
name
age
gender
'''
# d={'name':'Rambo','age':18,'gender':'male'}
# d_dit=d.__iter__()
# print(d_dit.__next__())
# print(d_dit.__next__())
# print(d_dit.__next__())
# print(d_dit.__next__()) # d_dit没有值了就会抛出异常(结束的信号)StopIteration
'''
name
age
gender
Traceback (most recent call last):
File "D:/text/迭代器.py", line 67, in <module>
print(d_dit.__next__())
StopIteration
'''
# f=open('a.txt','r',encoding='utf-8')
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# print(f.__next__())
# f.close()
'''
1

22

333

4444

55555

666666
Traceback (most recent call last):
File "D:/text/迭代器.py", line 84, in <module>
print(f.__next__())
StopIteration
'''
# l=['a','b','c']
# l_iter=l.__iter__()
# print(l_iter.__next__())
# print(l_iter.__next__())
# print(l_iter.__next__())
'''
a
b
c
'''
# d={'name':'Rambo','age':18,'gender':'male'}
# d_iter=iter(d)#d_iter=d.__iter__()
# # len(obj)=obj.__len__()
# while True:
# print(next(d_iter)) # print(d_iter.__next__())
# print(next(d_iter))
# print(next(d_iter))
'''
Traceback (most recent call last):
File "D:/text/迭代器.py", line 117, in <module>
print(next(d_iter)) # print(d_iter.__next__())
StopIteration
name
age
gender
'''
# d={'name':'Rambo','age':18,'gender':'male'}
# d_iter=iter(d)
# while True:
# try:
# print(next(d_iter))
# print(next(d_iter))
# print(next(d_iter))
# except StopIteration:
# break
'''
name
age
gender
'''
# for循环详解:
# 1、调用in后的obj.__iter__()
# 2、k=obj_iter.__next__()
# 3、捕捉StopIteration异常,结束迭代
# d={'name':'Rambo','age':18,'gender':'male'}
# for k in d:
# print(k)
'''
name
age
gender
'''
# 迭代器的优点:
# 提供一种统一的,不依赖于索引的取值方式,为for循环的实现提供了依据
# 迭代器同一时间只有一个值,更节省内存

# 迭代器的缺点:
# 只能往后取,并且是一次性的
# 不能统计值的个数,即长度
posted on 2019-12-04 20:44  OBOS  阅读(101)  评论(0编辑  收藏  举报