如果您创建了一个包含许多元素的列表,但只需要访问前几个元素,那么以下元素占用的空间将被浪费
[En]
If you create a list with many elements, but only need to access the first few elements, the space occupied by the following elements will be wasted
在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间。
在Python中,这种一边循环一边计算的机制,称为生成器:generator。
要创建一个generator,有很多种方法
第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:
L = [x * x for x in range(10)]
g = (x * x for x in range(10))
print(L)#
print(g)
```python
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
at 0x0000029277CA6AC0>