通过递归在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是空的。
def expand(node, hcList):
if node.hasTreasure():
hcList.append(node)
if not node.end():
expand(node.next(), hcList)
hcList = []
expand(startnode, hcList)
hcList.filter()
1 个回答
2
对于递归来说,通常返回一个新的值会更简单。
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
如果你的列表很深,可能会在堆栈上占用很多空间,但好的尾递归可以优化这个问题,让它变得更高效。