(待续)
生成器
yield是python中的一个关键字,类似于return,用于返回函数的返回值,然而yield返回的是一个生成器。生成器并不会一次返回所有结果,而是每次遇到yield关键字后返回相应结果,并保留函数当前的运行状态,等待下一次的调用。
例如:
def count(number):
while True:
yield number
number += 1
someNum = count(1)
for i in range(10):
print someNum.next()
运行结果:
1
2
3
4
5
6
7
8
9
10
yield返回的生成器属于迭代器,但普通迭代器不一定是生成器。
再例如:
def count():
nums = [1, 2, 3, 4, 5]
for item in nums:
yield item*item
a = [ _ for _ in count()]
print a
运行结果:
[1, 4, 9, 16, 25]
在生成器结束迭代后就会返回空,例如:
def count():
nums = [1,2,3]
for i in range(5):
yield nums[i: i+2]
a = [ _ for _ in count()]
print a
运行结果:
[[1, 2], [2, 3], [3], [], []]