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

在python中通过递归通过引用传递列表,python,list,pointers,recursion,reference,Python,List,Pointers,Recursion,Reference,我正在使用递归函数调用遍历一棵树,并希望将有价值节点的位置添加到主列表中。我目前的方法是使用全局搜索。我如何通过引用传递这个列表(或者在没有全局变量的情况下以另一种方式解决这个问题) 不管怎么说,在不使用毛茸茸的全局搜索引擎的情况下执行以下操作?我的实际代码与全局代码相比要混乱得多,但概念是相同的。下面的代码没有按我希望的方式工作。也就是说,hcList是空的 def expand(node, hcList): if node.hasTreasure(): h

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

不管怎么说,在不使用毛茸茸的全局搜索引擎的情况下执行以下操作?我的实际代码与全局代码相比要混乱得多,但概念是相同的。下面的代码没有按我希望的方式工作。也就是说,hcList是空的

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

hcList = []
expand(startnode, hcList)
hcList.filter()

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

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

如果列表很深,那么堆栈中可能有很多内容,但是好的尾部递归可以优化这些内容。

您的底部
展开
应该可以工作。问题出在别的地方。你有什么错误?列表上没有“filter”方法,所以这是个问题,是吗?列表总是通过引用传递的,所以我同意@roippi。问题在于你没有向我们展示的代码。是的,我验证了底部是否有效。我发现了原来的错误。谢谢
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