3 回答

TA貢獻1858條經驗 獲得超8個贊
您正在編寫代碼,就好像接收值并發送值一樣。這不是它的工作方式。所有收益都發送一個值并接收一個值。(yield)yield whatever
當生成器執行時,它分兩個階段執行。首先,的參數成為當前或調用的返回值,生成器暫停執行。如果沒有參數,則使用。這就是你的s來自哪里yieldyieldnextsendNoneNone
其次,當執行另一個 或 時,生成器將取消暫停,并且參數(或者如果使用)將成為表達式的值。nextsendsendNonenextyield
您正在嘗試使用一個來接收參數,并使用另一個來設置 的返回值。你需要使用一個 single 來設置一個返回值并接收下一個 的參數。例如yieldsendsendyieldsendsend
def get_square():
number = 0
while True:
number = yield number**2
或者,如果要使用單獨的 s 在生成器端發送和接收值,則需要使用單獨的(或)調用在另一端接收和發送值,并忽略 s。例如yieldsendnextNone
w.send(num)
num = next(w)
而不是 ,所以看起來像num = w.send(num)operations_pipeline
def operations_pipeline(numbers, operations, print_acum):
for num in numbers:
for w in operations:
w.send(num)
num = next(w)
print_acum.send(num)
for operation in operations:
operation.close()
print_acum.close()

TA貢獻1806條經驗 獲得超8個贊
def rooter():
number=0
while True:
number= yield math.floor(math.sqrt(number))
def squarer():
number=0
while True:
number= yield number**2
產量將給沒有嘗試這種方式
def accumulator():
number=0
while True:
number+= yield number

TA貢獻1827條經驗 獲得超8個贊
我相信你需要在這里的代碼中添加一個調用:nextoperations_pipeline
def operations_pipeline(numbers, operations, print_acum):
for num in numbers:
for i, w in enumerate(operations):
num = w.send(num)
next(w) # <<<--- this
沒有這個,我不相信它會回到第二次,假設你的第一個輸入是。get_square[square, accumulate]
添加回答
舉報