我的函数使用递归返回嵌套列表中目标出现的次数不起作用

问题描述

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,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
,

您需要使用递归调用的返回:

def count(x,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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...