nums =list()
a =0
b =1
i =0while i <10:
nums.append(a)
a, b = b, a + b
i +=1for num in nums:print(num)
2、使用迭代器实现
classFibonacci:def__init__(self, all_num):
self.all_num = all_num
self.current_num =0
self.a =0
self.b =1def__iter__(self):return self
def__next__(self):if self.current_num < self.all_num:
ret = self.a
self.a, self.b = self.b, self.a + self.b
self.current_num +=1return ret
else:raise StopIteration
fibo = Fibonacci(10)for num in fibo:print(num)
3、使用生成器实现
defcreate_num(all_num):
a, b =0,1
current_num =0while current_num < all_num:yield a
a, b = b, a + b
current_num +=1
obj = create_num(10)for num in obj:print(num)