python生成器generator

我们可以通过列表生成式生成列表,但受到内存的限制,列表的容量也是有限的;有时候,我们创建了一个有上百万元素的列表,但是访问的就仅仅只是前面几个元素,这样后面的元素就浪费了空间。
如果可以在循环的过程中就根据算法推算出后面的元素,这样不但不用生成一个完整的list,且节省了空间,generator生成器刚好可以做到这一点。
1、创建generator
generator的创建方式和列表生成式只有最外层括号不一样,列表是[],generator是(),其他都一致
>>> g = (n * n for n in range(0, 5))
2、打印generator的每个元素
第一种:使用next()函数,当没有元素时,继续调用next()函数会报StopIteration异的错误
>>> g = (n * n for n in range(0, 5))
>>> next(g)
0
>>> next(g)
1
>>> next(g)
4
>>> next(g)
9
>>> next(g)
16
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>
第二种:for循环遍历,因为generator也是可迭代对象,不需要关心StopIteration的错误。(正常情况下使用第二种方式)
>>> g = (n * n for n in range(0, 5))
>>> for n in g:
...     print(n)
...
0
1
4
9
16
>>>
3、yield关键字
当一个函数中出现yield关键字,那么这个函数就是一个generator
一般函数中遇到return就返回,generator则是在每次调用next()的时候,遇到yield就返回,且再次执行的时候会从上次yield返回的地方继续执行。
>>> def test():
...     print('one')
...     yield 1
...     print('two')
...     yield 2
...     print('three')
...     yield 3
...
>>> t = test()
>>> next(t)
one
1
>>> next(t)
two
2
>>> next(t)
three
3
>>> next(t)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值