首页 文章

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

提问于
浏览
3

我有一个列表中有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 . 但是,我不知道如何(如果可能)返回值而不停止递归 .

4 回答

  • 1

    你在找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)
    
  • 1

    你打算把它归还给谁?我的意思是如果你的线程忙于运行递归算法,谁得到“临时结果”来处理?

    最好的办法是调整算法,以便在再次递归之前包含一些处理 .

  • 6

    我不确定你要做什么,但你可以尝试通过使用yield语句以所需的时间间隔返回dict来制作递归生成器 . 要么将其复制到全球列表?

  • 1

    你有两个可能的解决方案:

    • 生成器方法:具有yield语句的函数,这可能是在递归函数中实现的麻烦 . (以phihags提案为例)

    • 回调方法:从递归内部调用辅助函数/方法,并可以通过第二个外部函数监视进度 .

    这里是一个非递归递归示例:;-)

    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)`
    ``

相关问题