生成器,generator,python中生成器有两种实现方法,分别是列表生成式和借助yield。
列表生成式
python中有一种方便强大的生成列表的方法,它可以把一个集合、一段连续的数等等生成一个列表。
下面举几个例子:
要把1~10的数字生成一个列表:
>>> [m*m for m in range(1,10)]
[1, 4, 9, 16, 25, 36, 49, 64, 81]
还可以进行运算之后再存入列表:
>>> [m for m in range(1,10)]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
还可以加上if判断:
>>> [m*m for m in range(1,10) if m%2==0]
[4, 16, 36, 64]
甚至还能支持多层循环:
>>> [m+n for m in range(1,10) for n in range(100,120)]
[101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128]
这就是简单强大的列表生成式。
那么怎么根据列表生成式产生生成器呢?
只需要把[]换成()
例如:
>>> l=[x*x for x in range(10)]
>>> l
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> k=(x*x for x in range(10))
>>> k
<generator object <genexpr> at 0x03401E30>
>>>
此时k中元素可以用next函数或者迭代器来使用:
>>> for i in k:
print(i)
0
1
4
9
16
25
36
49
64
81
>>> k=(x*x for x in range(10))
>>> next(k)
0
>>> next(k)
1
>>> next(k)
4
>>>
生成器还可以用yield实现:
l=[1]
yield l
while True:
l=[1]+[l[i]+l[i+1] for i in range(0,len(l)-1)]+[1]
yield l