1. 作用
列表生成器,减少存储空间
3. 操作
>>> l = [x * x for x in range(10)] # 列表
>>> l
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10)) # 生成器
>>> g
<generator object <genexpr> at 0x7f546bdb7c50>
>>> next(g) #利用next()调用
0
...
>>> next(g) # 没有了会报错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> g = (x * x for x in range(10))
>>> for n in g: # 利用for迭代
... print(n)
...
0
1
4
9
16
25
36
49
64
81
>>>
yield定义生成器
>>> n = 10
>>> while n > 0:
... yield n
... n += 1
...
File "<stdin>", line 2
SyntaxError: 'yield' outside function
>>> def func(n): # yield这家伙一定要在函数里,牛了隔壁
... while n > 0:
... yield n
... n += 1
...
>>> func(10)
<generator object func at 0x7f546bdb7c50>
>>>
网友评论