简体   繁体   English

通过递归查找列表深度时出现全局变量问题

[英]Trouble with global variable while list depth finding via recursion

I have a recursion function with a global variable for checking list depth, it works correct until you start it double or more times because variable doesn't reset.我有一个递归 function 和一个用于检查列表深度的全局变量,它可以正常工作,直到你启动它两次或更多次,因为变量不会重置。 I've already seen the simplest way, but can I repair my code for correct work or it's just piece of dead code?已经看到了最简单的方法,但是我可以修复我的代码以使其正常工作还是只是一段死代码? Oh, I really have troubles with recursion..哦,我真的有递归的麻烦..

depth = 1
def list_depth(arr):
    global depth
    for element in arr:
        # print(type(element))
        if type(element) == list:
            depth += 1
            list_depth(element)
        else:
            continue
        return depth
    return depth

print(list_depth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1])) # => 6 correct
print(list_depth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1])) # => 11 wrong

there are a few ways you could go about it... if you really want to keep your code as it is you'll have to reset depth before each call like this:depth方法可以让您了解它...

print(list_depth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1]))
depth=1
print(list_depth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1]))

output: output:

6
6

but a better solution could be sending depth as one of the function arguments instead of declaring it as a global argument但更好的解决方案可能是将深度作为 function arguments 之一发送,而不是将其声明为全局参数

this should do the trick:这应该可以解决问题:

def list_depth(arr,depth=1):
    for element in arr:
        # print(type(element))
        if type(element) == list:
            depth += 1
            return list_depth(element,depth)
        else:
            continue
    return depth

print(list_depth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1])) 
print(list_depth([1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1]))

output: output:

6
6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM