python_迭代补充

yield:跟return差不多,但是可以返回多个值,每次使用yield都会返回到上次收到yield后面

效率更高,举个例子

def eat():
    ke = []
    for i in range(100):
        ke.append('包子%s' %i)
    return ke
list_eat = eat()
print(list_eat)
View Code
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__())
View Code
#生成器函数
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个包子全部做完才能吃,效率比较低

posted @ 2019-07-09 15:00  Alom  阅读(96)  评论(0编辑  收藏  举报