我的函数使用递归 return 嵌套列表中 target 的出现次数不起作用

My function using recursion to return the number of occurrences of target in a nested list doesn't work

def count(x, nxs, counter=0):

    for e in nxs:
        if type(e) == type([]):
            count(x, e)
        else:
            if e == x:
                counter += 1

    return counter

print(count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]]))

这会打印 1 而不是 4。

您需要显式地将计数器变量传递给递归函数

def count(x, nxs, counter=0):

    for e in nxs:
        if type(e) == type([]):
            counter = count(x, e, counter)
        else:
            if e == x:
                counter += 1

return counter

你需要使用递归调用的return:

def count(x, nxs, counter=0):
    for e in nxs:
        if type(e) == type([]):
            counter += count(x, e)
        else:
            if e == x:
                counter += 1

    return counter

由于counter在本地使用,您应该将其从参数列表中删除:

def count(x, nxs):
    counter = 0
    for e in nxs:
        if type(e) == type([]):
            counter += count(x, e)
        else:
            if e == x:
                counter += 1

    return counter