Python 学习笔记 -- 生成器
#定义一个生成器,形式与函数相同,区别在于yield关键字,它其实类似于return def easyYield(): yield 1 yield 2 #将生成器实例化一个对象,绑定在变量身上,通过next取得yield的内容 a = easyYield() print(next(a)) print(next(a)) #第二个实例,升级版的生成器 def libs(): a,b=0,1 while True: a,b = b,a+b yield a for each in libs(): if each > 100: break print(each,end=",") print("-----------------------------------------------------") #列表推导式 a = [i for i in range(100) if not(i % 2) and i % 3] print(a) #字典推导式 b = {i:i%2==0 for i in range(10)} print(b) #集合推导式 c = {i for i in [1,2,1,3,12,4,2,2,4,5,3,5]} print(c) #生成器推导式 d = (i for i in range(10)) print(next(d)) print(next(d))