如何在不停止递归的情况下返回递归函数中的值?

Nie*_*ein 3 python recursion return

我有一个列表中有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
Run Code Online (Sandbox Code Playgroud)

这是有效的,但我最终得到了一个巨大的列表.我宁愿在每轮递归时返回itemDict.但是,我不知道如何(如果可能)返回值而不停止递归.

phi*_*hag 6

您正在寻找yield:

def tupleToDict(listOfList):
    yield getItems(listofList)
    for nestedList in listOfList:
        for el in getAllNestedItems(nestedList):
            yield el
Run Code Online (Sandbox Code Playgroud)

在Python 3.3+中,您可以用a替换最后两行yield from.

您可能希望重写您的函数以进行迭代:

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