1. 程式人生 > >phthon生成器的使用

phthon生成器的使用

not ring -h 函數定義 post feel side caption 交互

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函數是可以改變根據客戶端代碼改變自身行為的

phthon生成器的使用