Python中的generator函数出现的目的是节省计算机内存空间,其作用是一边生成,一边计算,这样就避免了把所有数组一次生成好并且一次性存入内存的隐患。generator一般被称为生成器。
- 普通方式生成列表
list_a = [x*x*x for x in range(3)]
print list_a
[0, 1, 8]
- 生成器
list_b = (x*x*x for x in range(3))
print list_b
<generator object <genexpr> at 0x10a2229b0>
>>> print list_b.next()
0
>>> print list_b.next()
1
>>> print list_b.next()
8
>>> print list_b.next()
-----------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-36-c031a72f3d97> in <module>()
----> 1 print list_b.next()
StopIteration:
- for循环生成器
list_b = (x*x*x for x in range(3))
print list_b
for i in list_b:
print i
<generator object <genexpr> at 0x10a222b90>
0
1
8