2014-02-11 89 views
0

我有一臺發電機方法next_item(data)用於發電機

我把它在一個循環的代理方法:

for count, item in enumerate(next_item(data)): 
    # do something here 

但現在我想延長我的計劃 - 到餐桌的next_item方法爲兩種方法基於輸入。

所以NEXT_ITEM()是這樣的:

if ...: # some condition here 
    yield(next1(data)) # or return(next1(data)) ?? 
else: 
    yield(next2(data)) 

但回報不工作("SyntaxError: 'return' with argument inside generator")yield顯然通向項作爲一個發電機來代替這臺發電機的項目。

所以我將不得不重構調用腳本,但我想知道是否有辦法編寫這樣的代理生成器。

+2

_ 「但回報不工作」 _。你是否用回報取代了第一個「yield」?還是你們兩個都取代?你能發佈產生該錯誤的實際代碼嗎? – Kevin

+0

我不清楚你想要做什麼。 'next1'和'next2'常規函數,或者它們自己?如果你想代理一個生成器,你可以這樣做:'if ...:yield next1(data).next()'etc ...或者返回生成器的輸出,例如:if ...:return next1(data) '...... –

+0

凱文:我只換了一個,是的,那是問題所在。謝謝你的幫助! – galapah

回答

4

從你的錯誤信息,這聽起來像你想是這樣:

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() 
+0

是的,那正是我所做的 - 我只是通過回報取代了兩種產量中的一種。我從錯誤中沒有意識到這是問題所在。謝謝! – galapah