從你的錯誤信息,這聽起來像你想是這樣:
if ...: # some condition here
return (next1(data))
else:
yield (next2(data))
Python會不會接受,無論產量和收益的功能。如果您希望它可以工作,則需要將兩個收益率更改爲收益率。
這裏是兩臺發電機之間選擇一個函數的例子:
def squares():
i = 0
while True:
yield i * i
i += 1
def evens():
i = 0
while True:
yield i*2
i += 1
def next_item(switch):
if switch == 0:
return squares()
else:
return evens()
print "printing squares..."
for idx, item in enumerate(next_item(0)):
print idx, item
if idx > 10: break
print "printing evens..."
for idx, item in enumerate(next_item(1)):
print idx, item
if idx > 10: break
結果:
printing squares...
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
11 121
printing evens...
0 0
1 2
2 4
3 6
4 8
5 10
6 12
7 14
8 16
9 18
10 20
11 22
如果你願意,你可以讓next_item
發電機以及:
def next_item(switch):
if switch == 0:
for item in squares(): yield item
else:
for item in evens(): yield item
或者可能:
def next_item(switch):
for item in squares() if switch == 0 else evens():
yield item
如果你正在使用3.X,你可以使用yield from
:
def next_item(switch):
yield from squares() if switch == 0 else evens()
_ 「但回報不工作」 _。你是否用回報取代了第一個「yield」?還是你們兩個都取代?你能發佈產生該錯誤的實際代碼嗎? – Kevin
我不清楚你想要做什麼。 'next1'和'next2'常規函數,或者它們自己?如果你想代理一個生成器,你可以這樣做:'if ...:yield next1(data).next()'etc ...或者返回生成器的輸出,例如:if ...:return next1(data) '...... –
凱文:我只換了一個,是的,那是問題所在。謝謝你的幫助! – galapah