簡體   English   中英

通過遞歸在python中通過引用傳遞列表

[英]Pass list by reference in python through recursion

我正在使用遞歸函數調用來遍歷樹,並且想將有價值的節點的位置添加到主列表中。 我當前的方法是使用全局。 我如何通過引用傳遞此列表(或以其他方式解決此問題而不使用全局變量)

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

對於遞歸,返回新值通常更簡單

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

如果列表很深,則可能有很多問題,但是良好的尾部遞歸可以優化這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM