phthon生成器的使用

python生成器

python生成器

python生成器基于yield语句,生成器可以暂停函数并返回一个中间结果。该函数会保存执行上下文,稍后必要时可以恢复。

def fibonacci():
a,b=0,1
while True:
yield b
a,b=b,a+b
fib=fibonacci()
next(fib)#输出的是b,与迭代器的使用相同,用next函数。
#fibonacci()函数返回一个生成器对象,是特殊的迭代器,他知道如何保存执行上下文。他可以被无限次调用,每次都会生成序列的下一个元素。
def power(values):
for value in values:
print("powering %s"%value)
yield value
def adder(values)
for value in values:
print("adding to %s"%value)
if value%2==0:
yield value+3
else:
yield value+2
elements=[1,4,7,9,12,19]
results=adder(power(elements))
next(results)

生成器的另一个重要的特性,就是能够利用next函数与调用的代码进行交互,yield变成一个表达式,而值可以通过名为send的新方法传递

def psychologist():
print("Please tell me you problem")
while True:
ans=(yield)
if ans is not None:
if ans.endswith('?'):
print("Don't ask yourself too much questions")
elif 'good' in ans:
print("ahh that's good,go on")
elif 'bad' in ans:
print("Don't be so negative")
free=psychologist()
next(free)
free.send("I feel bad")

send的作用与next类似,但会将函数定义内部的值变成yield的返回值。使用send函数是可以改变根据客户端代码改变自身行为的

posted @ 2017-12-31 16:57  Doctor_Bool  阅读(266)  评论(0编辑  收藏  举报