Python生成器基本用法
本示例解析了Python生成器(generator)的具体应用方式,旨在为读者提供实用的参考代码与说明。
借助yield关键字,函数能够产生一系列结果数据,而不是仅返回单个数值。
具体实现如下所示:
def countdown(n):
print "counting down"
while n>0:
yield n #生成一个n值
n -=1
>>> c = countdown(5)
>>> c.next()
counting down
5
>>> c.next()
4
>>> c.next()
3
调用next()会驱动生成器函数执行至下一个yield语句处,此时next()接收yield返回的值,同时函数暂停执行。再次调用next()时,函数从暂停处继续执行后续代码,直至函数结束。
实际开发中,通常不手动调用next(),而是通过for循环来迭代生成器,例如:
>>> for i in countdown(5):
... print i
...
counting down
5
4
3
2
1
next()和send()方法的返回值均对应yield表达式之后的部分。两者的区别在于:send()可向(yield n)表达式发送一个参数,该参数成为赋值给m的值;而next()则向(yield n)表达式发送None。需注意区分调用next()/send()时的返回值与(yield n)本身的返回值,二者不同,可通过输出结果加以辨别。
def h(n):
while n>0:
m = (yield n)
print "m is "+str(m)
n-=1
print "n is "+str(n)
>>> p= h(5)
>>> p.next()
5
>>> p.next()
m is None
n is 4
4
>>> p.send("test")
m is test
n is 3
3
希望上述内容能对读者的Python编程实践有所助益。