通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。
Python中,一边循环一边计算的机制,称为生成器:generator。
创建生成器generator的方法有很多:
- 将列表生成式的 [] 改为 () 就是一个生成器generator啦
In [35]: l = [x*x for x in range(11)] In [36]: l Out[36]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100] In [37]: g = (x*x for x in range(11)) In [38]: g Out[38]: <generator object <genexpr> at 0x0000026DC9963C50> In [39]: next(g) Out[39]: 0 In [40]: next(g) Out[40]: 1 In [41]: next(g) Out[41]: 4 ...... In [49]: next(g) Out[49]: 100 In [50]: next(g) ---------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-50-e734f8aca5ac> in <module>() ----> 1 next(g) StopIteration:
生成器是可以用next()函数进行取值的
- 函数中有yield关键字,那么函数就是生成器
In [4]: def odd(): ...: print("step 1") ...: yield 1 ...: print("step 2") ...: yield 2 ...: print("step 3") ...: yield 3 ...: print("step 5") ...: In [5]: o = odd() In [6]: o Out[6]: <generator object odd at 0x000001748261AE60>
可以使用next()进行取值
In [7]: next(o) step 1 Out[7]: 1 In [8]: next(o) step 2 Out[8]: 2 In [9]: next(o) step 3 Out[9]: 3 In [10]: next(o) step 5