迭代器

1.1 可迭代对象(Iterator)
迭代器协议:某对象必须提供一个__next__()方法,执行方法要么返回迭代中的下一项,要么引起一个Stopiteration异常,以终止迭代(只能往后走,不能往前退)

协议是一种规范,可迭代对象实现了迭代器协议,python的内部工具(如for循环、sum、min、max函数),使用迭代器协议访问对象

可迭代对象(Iterator):实现了迭代器协议的对象(如何实现:对象内部定义了一个__iter__()方法),也就是可迭代对象内部要包含__iter__() 函数

迭代器(Iterator):内部包含了__iter()() ,同时也包含__next()

1.2 for循环的工作机制
先通过__iter__()方法将可迭代对象转换为迭代器,再调用迭代器中的__next__()方法遍历,最后再抓取结束时的异常

print("解析for循环的工作机制:")
num = [1, 2, 3, 4, 5]
for i in num: # 工作机制: num.iter() ------> num.next()
print(i)
1.3 可迭代对象与迭代器
1)可迭代对象与迭代器之间的关系

可迭代对象包含迭代器
如果一个对象拥有__iter__方法,其就是可迭代对象(可以被for循环迭代);如果一个对象拥有next方法,其是迭代器
定义可迭代对象,必须事先__iter__方法;定义迭代器,必须实现__iter__和next方法。
2)迭代器的特点

节省内存
惰性机制
不能反复,只能向下执行
3)isinstance()判断对象是否为Iterable对象:

from collections import Iterable
print(isinstance([], Iterable))
1.4 迭代器协议的使用示例
print("使用while循环遍历一个列表:")
index = 0
while index < len(num):
print(num[index])
index += 1

print("利用迭代器协议遍历一个列表:")
iter = num.iter()
print(iter.next())
print(iter.next())
print(iter.next())

print("解析文件操作中对于文件内容的遍历:")
f = open("test.txt", "r")
f_iter = f.iter() # 这里先将整个文件转换为一个迭代器,之后对迭代器调用__next__()方法,只在有需要的时候才加载文件一行内容

当取出一行内容时,因为没有赋值给任何变量,所以占用的内存会被python的自动回收机制回收,所以这种遍历文件的方式只会动态的占用一小块内存

print(f_iter.next(), end="")
print(f_iter.next(), end="")
print(f_iter.next(), end="")
print(f_iter.next(), end="")
print(f_iter.next(), end="")
f.close()

print("next()方法:") # next()方法--->调用__next__()方法
the_num = [1, 2, 3]
the_iter = the_num.iter() # 也可以直接使用iter(the_num)方法
print(next(the_iter)) # next(the_iter) -----> 调用 the_iter.next()

原文地址:https://www.cnblogs.com/chen991126/p/14122068.html