簡體   English   中英

python 使用遞歸查找列表的深度

[英]python finding depth of a list using recursion

我需要使用遞歸找到列表的深度,但我不能使用全局變量或有多個參數。 這是我擁有的代碼,但出現了無法調用深度的錯誤,因為我無法使用全局變量,並且當我在 function 中調用它時,遞歸發生時它只是重置了變量

def how_deep(list_of_lists):
    for i in list_of_lists:
        if type(i) == list:
            how_deep(i)
            depth += 1
        else:
            print(depth)


if __name__ == '__main__':
    print(how_deep([[[], [], [], [[[]]]], []],))
    print(how_deep([]))
    print(how_deep([[], []]))
    print(how_deep([[[]], [], [[]], [[[]]]]))
    print(how_deep([[[[], [[]], [[[]]], [[[[]]]]]]]))
    print(how_deep([[[], []], [], [[], []]]))

當您遍歷每個項目時,您要記錄其最大深度並返回列表中單個子項的最大深度。 你可以這樣做:

def how_deep(list_of_lists):
    if not isinstance(list_of_lists, list):
        return 0
    return max(map(how_deep, list_of_lists), default=0) + 1

暫無
暫無

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

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