生成器及yeild

  • 关于yield

网上关于yield的文章很多,这里就不在赘述了,总结2点,yield是生产很产出的意思,也就是生成器,一个函数中出现yield那么他就是生成器

yield除了实现return功能,还阻塞了程序,当使用next再一次调用的时候才从阻塞位置向后继续执行

def fun1(n) :
    print('程序开始!')
    while n > 0 :
        re = yield n
        n = n - 1
        print(re)
        print('*' * 10)


f=fun1(5)
print(next(f))
print(next(f))

返回结果如下:

程序开始!
5
None
**********
4

Process finished with exit code 0

这里能够很好的解释yield的return作用和阻塞作用,第一个return只返回程序开始和5,5相对于return的返回作用,程序就阻塞在这里了,第二次调用next,程序接着开始,re变量接受的是空值,所以返回none,

接着输出一排************⭐花,重新进入循环,并返回4,又阻塞了!

使用yield的好处就是代码简介,不用定义一个Itrable类,和list相比又比较节约内存。

  • 实现fibonacci函数

def fibonacci(n):
    a = 0
    b = 1
    while n > 0:
        yield b
        a, b = b, a + b
        n -= 1
        print('*'*10)


f = fibonacci(5)
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))

#print(next(f))

返回结果如下:

1
**********
1
**********
2
**********
3
**********
5

执行第6次print时会出现下面结果及错误最后结束:

**********
Traceback (most recent call last):
  File "/Users/apple/Desktop/python09/day1/生成器.py", line 35, in <module>
    print(next(f))
StopIteration

Process finished with exit code 1

完整代码及测试结果如下:

def fibonacci(n):
    a = 0
    b = 1
    while n > 0:
        yield b
        a, b = b, a + b
        n -= 1
        

f = fibonacci(5)
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print('*'*8)
for i in f:
    print(i)
print('*'*12)
f = fibonacci(4)
for i in f:
    print(i)
print('*'*14)


输出结果如下:
1
1
2
3
5
********
************
1
1
2
3
**************

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值