zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python生成器详解编程语言

Python编程语言 详解 生成器
2023-06-13 09:20:38 时间

#练习使用生成器
print( 杨辉三角效果图: )
def triangles(max):
n=1
T=[1]
yield T
while n max:
T=[1]+[T[i-1]+T[i] for i in range(1,n)]+[1]
#print( before step )
yield T #程序每执行到yield处时,会返回生成的结果,等下一次循环时接着向下执行,而不是从头开始执行
#print( next step )
n=n+1
value = triangles(5) #不循环遍历就不会执行,需手动执行next === 惰性执行
for res in value:
print(res)
#print(value)
#next(value) #循环遍历后不能再调用next,因为已经指向最末尾了
#next(value)

测试结果:

Python生成器详解编程语言

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/13013.html

c