yield:跟return差不多,但是可以返回多个值,每次使用yield都会返回到上次收到yield后面
效率更高,举个例子
def eat(): ke = [] for i in range(100): ke.append('包子%s' %i) return ke list_eat = eat() print(list_eat)
l = ('包子%s'%i for i in range(1,101)) print(l.__next__()) print(l.__next__()) print(l.__next__()) print(l.__next__()) print(l.__next__()) print(l.__next__()) print(l.__next__()) print(l.__next__()) print(l.__next__()) print(l.__next__())
#生成器函数 def moce(): for i in range(100): yield '来一个人吃包子%s' %i dec = moce() print(dec.__next__()) print(dec.__next__()) print(dec.__next__()) print(dec.__next__()) print(dec.__next__()) print(dec.__next__()) print(dec.__next__()) print(dec.__next__())
后者两者则是做出一个包子就吃,而前者是要等100个包子全部做完才能吃,效率比较低