Python yield生成器 函数

一般而言包含yield关键词的函数就是生成器函数,生成器函数最终返回的是一个生成器。

 

>>> def count_num():
...     yield 1
...     yield 2
...     yield 3
...     yield 4
...     return
... num=count_num()
#
# 调用next()依次向下取值,yield类似return,中断流程,记录返回当前的值,
#一直往下执行,直到执行生成器函数中的return触发生成器对象抛出stopiteration异常,
# 再往下取值就为空了。
>>> next(num)
1
>>> next(num)
2
>>> next(num)
3
>>> next(num)
4
>>> next(num)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
StopIteration


def output_ab():
    print("start flag")
    yield "a"
    print("continue flag")
    yield "b"
    print("end")
output=output_ab()
print(next(output))
start flag
a
print(next(output))
continue flag
b
print(next(output))
end
Traceback (most recent call last):
  File "<input>", line 1, in <module>
StopIteration
def output_num():
    for r in range(6):
        yield r
num=output_num()
print(next(num))
0
print(next(num))
1
print(next(num))
2
print(next(num))
3
print(next(num))
4
print(next(num))
5
print(next(num))
Traceback (most recent call last):
  File "<input>", line 1, in <module>
StopIteration
#生成器表达式
new_num=(x*x for x in output_num())
print(next(new_num))
0
print(next(new_num))
1
print(next(new_num))
4
print(next(new_num))
9
print(next(new_num))
16
print(next(new_num))
25
print(next(new_num))
Traceback (most recent call last):
  File "<input>", line 1, in <module>
StopIteration

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值