1.使用for遍历list数组
# 使用for遍历list数组
nums = list()
a = 0
b = 1
i = 0while i < 10:nums.append(a)a, b = b, a+bi += 1for num in nums:print(num)
2.使用迭代器完成
class Fibonacci(object):def __init__(self, all_num):self.all_num = all_numself.current_num = 0self.a = 0self.b = 1def __iter__(self):return selfdef __next__(self):if self.current_num < self.all_num:ret = self.aself.a, self.b = self.b, self.a+self.bself.current_num += 1return retelse:raise StopIterationfibo = Fibonacci(10)for num in fibo:print(num)
3.使用生成器完成
def create_num(all_num):a, b = 0, 1current_num = 0while current_num < all_num:yield a # 如果一个函数中有yield语句,那么这个就不在是函数,而是一个生成器的模板a, b = b, a+bcurrent_num += 1# 如果在调用create_num的时候,发现这个函数中有yield那么此时,不是调用函数,而是创建一个生成器对象
obj = create_num(10)for num in obj:print(num)
运行结果:
0
1
1
2
3
5
8
13
21
34