通过递归在python中引用传递列表

2024-09-26 17:39:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用递归函数调用遍历树,我想将有价值节点的位置添加到主列表中。我目前的方法是使用全局。我如何通过引用传递这个列表(或者用另一种没有全局变量的方法来解决这个问题)

hcList = []

def expand(node):
    global hcList

    if node.hasTreasure():
        hcList.append(node)
    if not node.end():
        expand(node.next())

global hcList
expand(startnode)
hcList.filter()

不管怎样,在不使用毛茸茸的球的情况下做下面的事情?我的实际代码对全局变量的处理要混乱得多,但概念是相同的。下面的代码没有按我希望的方式工作。也就是说,hcList是空的。在

^{pr2}$

Tags: 方法代码node列表if节点def全局
1条回答
网友
1楼 · 发布于 2024-09-26 17:39:20

对于递归,返回新值通常更简单

def expand(node, hcList):
    if node.hasTreasure:
         hcList.append(node)
    if node.end():
         return hcList
    return expand(node.next(), hcList)

hcList = expand(startnode, [])
hcList.filter() # not sure why this was in the OP

如果你的列表很深,你可能有很多东西在堆栈上,但是良好的尾部递归可以优化这些东西。在

相关问题 更多 >

    热门问题