'''
迭代器和生成器的例子
'''
# 迭代器
'''
注意点:
(1)list、tuple、dict都是Iterable(可迭代对象),但不是Iterator(迭代器对象)。
可以使用内建函数iter(),把这些都变成Iterable(可迭代器对象)。
(2)_iter_(self)只会被调用一次,而_next_(self)会被调用 n 次,直到出现StopIteration异常。
https://blog.csdn.net/u014745194/article/details/70176117
'''
class Fibonacci_iter(object):
def __init__(self, max_value):
super(Fibonacci_iter, self).__init__()
self.max_value = max_value
def __iter__(self):
self.a = 0
self.b = 1
return self # 需要返回一个迭代器
def __next__(self):
fib = self.a
if fib >= self.max_value:
raise StopIteration
self.a, self.b = self.b, self.a+self.b
return fib
def get_fib_iterator(max_value):
fib = Fibonacci_iter(max_value)
res = []
for i in fib:
res.append(i)
return res
# 生成器
'''
https://www.runoob.com/python3/python3-iterator-generator.html
'''
def Fibonacci_generator(n):
a, b, counter = 0, 1, 0
while True:
yield a
a, b = b, a+b
counter += 1
if counter >= n:
return
def get_fib_generator(max_value):
fib = Fibonacci_generator(max_value)
res = []
for i in fib:
res.append(i)
return res
if __name__ == "__main__":
res1 = get_fib_iterator(20)
res2 = get_fib_generator(20)
print(res1)
print(res2)
python迭代器和生成器实现斐波那契数列
最新推荐文章于 2022-05-24 10:48:53 发布