可迭代对象和迭代器
nums = [1, 2, 3] # 列表是可迭代对象
it = iter(nums) # 拿到迭代器
print(next(it)) # 1
print(next(it)) # 2
取完会抛 StopIteration。for 循环内部其实就是自动帮你调用了 iter() 和 next()。
自己写一个迭代器
class Countdown:
def __init__(self, start):
self.cur = start
def __iter__(self):
return self
def __next__(self):
if self.cur < 0:
raise StopIteration
v = self.cur
self.cur -= 1
return v
生成器更省事
def countdown(n):
while n >= 0:
yield n
n -= 1
print(list(countdown(3))) # [3, 2, 1, 0]
本站提示:生成器不会一次性把所有值装进内存,处理大文件或无限序列时特别有用。
本文根据 W3School Python 教程 的知识点重新整理、补充示例编写,非原文转载。