一、 迭代器
Python中只要实现了__iter__和__next__方法的对象都可以称之为迭代器,迭代器是一个带状态的对象,可以记录迭代的位置。
#!/usr/bin/env python3
class Iterator:
def __iter__(self):
self.counter = 0
self.a = 0
self.b = 1
return self
def __next__(self):
if self.counter < 20:
tmp = self.a
self.counter = self.counter + 1
self.a, self.b = self.b, self.a+self.b
return tmp
else:
raise StopIteration
iterclass = Iterator()
it = iter(iterclass)
for d in it:
print(d, end=" ")
print()
输入结果:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
二、 生成器
Python中的生成器是一种特殊的迭代器,因为生成器生成的是一个迭代器对象,而这个迭代器中只有一个值,也就是说生成器生成的这个迭代器只可以迭代一次。例如我们对一个函数使用yield关键字进行值得返回,就可以实现Python简单的生成器。
#!/usr/bin/env python3
def fib(n):
a, b, counter = 0, 1, 0
while True:
if counter > n:
return
yield a
a, b = b, a+b
counter = counter + 1
f = fib(20)
while True:
try:
print(next(f), end=" ")
except StopIteration:
break
print()
输入结果:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181