簡體   English   中英

如何在不停止遞歸的情況下返回遞歸函數中的值?

[英]How can I return values in a recursive function without stopping the recursion?

我有一個列表中有x個列表的結構,每個列表都有x個元組。 我事先不知道有多少嵌套列表,或者每個列表中有多少元組。

我想在所有元組中使用字典,因為我不知道列表的深度我想使用遞歸。 我做的是

def tupleToDict(listOfList, dictList):
    itemDict = getItems(list)  # a function that makes a dictionary out of all the tuples in list
    dictList.append(itemDict)
    for nestedList in listOfList:
         getAllNestedItems(nestedList, dictList)

    return dictList

這是有效的,但我最終得到了一個巨大的列表。 我寧願在每輪遞歸時返回itemDict。 但是,我不知道如何(如果可能)返回值而不停止遞歸。

你在尋找yield

def tupleToDict(listOfList):
    yield getItems(listofList)
    for nestedList in listOfList:
        for el in getAllNestedItems(nestedList):
            yield el

在Python 3.3+中,您可以使用yield from替換最后兩行。

您可能希望重寫您的函數以進行迭代:

def tupleToDict(listOfList):
    q = [listOfList]
    while q:
        l = q.pop()
        yield getItems(l)
        for nestedList in listOfList:
            q += getAllNestedItems(nestedList)

你打算把它歸還給誰? 我的意思是如果你的線程忙於運行遞歸算法,誰得到“臨時結果”來處理?

最好的辦法是在再次遞歸之前調整算法以包含一些處理。

我不確定你要做什么,但你可以嘗試通過使用yield語句以所需的時間間隔返回dict來制作遞歸生成器。 要么將其復制到全球列表?

你有兩個可能的解決方案:

  1. 生成器方法:具有yield語句的函數,這可能是在遞歸函數中實現的麻煩。 (以phihags提案為例)

  2. 回調方法:從遞歸內部調用輔助函數/方法,並可以通過第二個外部函數監視進度。

這里是一個非遞歸遞歸示例:;-)

def callback(data): print "from the depths of recursion: {0}".format(data)

 def recursion(arg, callbackfunc): arg += 1 callbackfunc(arg) if arg <10: recursion(arg, callbackfunc) return arg print recursion(1, callback) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM