我终于开始在Python中进行递归,并尝试在alist中计算目标数的出现次数。但是,我遇到了在嵌套的list数字中计算出现次数的问题。
例如

def count(lst, target):

    if lst == []:
        return 0
    if lst[0] == target:
        return 1 + count(lst[1:], target)
    else:
        return 0 + count(lst[1:], target)

输出
>>> count( [1,2,3,[4,5,5],[[5,2,1],4,5],[3]], 1 )
Output: 1
Expected output: 2
有没有一种简单的方法可以在Python中展开嵌套列表?或者用一种简单的方法来解释我的代码中有一个嵌套列表这一事实?

最佳答案

def count(lst, target):
    n = 0
    for i in lst:
        if i == target:
            n += 1
        elif type(i) is list:
            n += count(i, target)
    return n

关于python - 递归计数嵌套数字列表中的出现次数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35448323/

10-08 22:02
查看更多