生成器:生成器属于迭代器,通过next()方法取值,可以用于for循环,通过yield可以自定义生成器。
例:
>>> def test_yield(n):
... i = 0
... while i <n:
... yield i**2
... i+=1
...
>>> g1 = test_yield(10)
>>> g1
<generator object test_yield at 0x7f1eeaefbaa0> ########g1为生成器
>>> g1.next()
0 ##生成器通过next()方法取值,每次g1调用函数时,当遇到yield时,函数停止,再次执行next()函数时,取下一个值(i**2)
>>> g1.next()
1
>>> g1.next()
4
>>> g1.next()
9
>>> g1.next()
16
>>> g1.next()
25
>>> g1.next()
36
>>> g1.next()
49
>>> g1.next()
64
>>> g1.next()
81
>>> g1.next() ##########取值结束,抛出异常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration