在Python中,这种一边循环一边计算的机制,称为生成器:generato
创建一个生成器
# g=(x for x in range(100)) #创建一个生成器 # print(next(g))#用next()调用生成器 # print(next(g)) # print(next(g)) # print(next(g)) # 或 # for i in g: #通过迭代来调用生成器 # print(i)
或
生成器保存的是算法,每次调用next()就计算出g的下一个元素的值,直到最后一个元素
生成器还可以通过函数来实现
如:斐波拉契数列除第一个和第二个数外,任意一个数都可由前两个数相加得到:
# def fid(n): # a = 1 # b = 1 # while n: # yield a #相当于一个不会停止的return # a,b=b,a+b # n=n-1 #或 # def fid(max): # n,a,b=0,0,1 # while n<max: # yield b # a,b=b,a+b #赋值语句相当于 t=(b,b+a) a=t[0] b=t[1] # n=n+1 # for j in fid(10): # print(j)
如果一个函数定义中包含yield
关键字,那么这个函数就不再是一个普通函数,而是一个生成器(generator)
杨辉三角
# def yanghui(n):#定义一个函数,函数参数为n # list1=[1] # for i in range(n): # 循环确定杨辉三角列数 # yield list1 # 输出列表list1 # list2=[1] # for j in range(len(list1)-1): # 循环确定list1的下标 # list2.append(list1[j]+list1[j+1])#将list1 中相邻两个下标对应的值相加后添加到list2中 # list2.append(1)#在list2的末尾添加元素1 # list1=list2#将list2的值赋予list1 # for j in yanghui(10): # print(j)