# 迭代器:重复做某事情
# l=['a','b','c','d','e']
#
# # for要有下标才能使用下面的语句,查文件,字典都用不了
# for i in l:
# print(i)
#
# i=0
# while i in range(len(l)):
# print(l[i])
# i+=1
# 如果没下标,就要用迭代器
# d={"a":1,"b":2,"c":3}
# # 只要能选到iter方法,就是能迭代
# i=d.__iter__()
# print(i.__next__())
# print(i.__next__())
# print(i.__next__())
# d={"a":1,"b":2,"c":3}
# i=d.__iter__()
# # 也可以i=iter(d)
# while True:
# try:
# print(next(i))
# except StopIteration:
# break
# l=['a','b','c','d','e']
# i=l.__iter__()
#
# while True:
# try:
# print(i.__next__())
# except StopIteration:
# break
#
# # for也可以迭代,k in l其实是l.__iter__()
# l=['a','b','c','d','e']
# for k in l:
# print(k)
#
# s=('a','b','c','d')
# for k in s:
# print(k)
# s={"a":1,"b":2,"c":3}
# for k in s:
# print(k)
# print(s[k])
# with open('b.txt','r') as f:
# for line in f:
# print(line)
#
# with open('b.txt',"r") as f:
# i=f.__iter__()
# while True:
# try:
# print(next(i))
# except StopIteration:
# break
# 为什么要用迭代器
# 优点:
# 1、迭代器提供了一种不依赖索引的取值方式,可以用到集合,字典等
# 2、迭代器与列表比较,迭代器是惰性计算,更节省内存
# 缺点:
# 1、列表可以直接取第3个,而迭代器要把1、2、3个都取了才能取第3个
# 2、不知道列表的长度
l=[1,2,3,4]
print(len(l))
i=iter(l)
print(next(i))
print(next(i))
print(next(i))
print(next(i))
for x in i:
print(x)
# 再执行就没值了,因为迭代器都是next地取值
for x in i:
print(x)
# 查看可迭代的对象
s="hello"
l=[1,2,33]
t=(1,2,3)
d={"a":1}
se1t={1,2,3,4,5}
f=open('a.txt')
# 看看是否迭代器
from collections import Iterator
print(isinstance(s,Iterator))