递归计算嵌套数字列表中的出现次数

Recursively counting occurrences in a nested list of numbers

我终于开始在 Python 中进行递归并尝试计算 list 中目标数字的出现次数。但是,我 运行 遇到了计算嵌套 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 中展平嵌套列表?或者我可以用一种简单的方法来说明我的代码中存在嵌套列表这一事实?

你只需要一个额外的案例来处理 lst[0] 是一个子列表,比如:

def count(lst, target):

    if lst == []:
        return 0
    if lst[0] == target:
        return 1 + count(lst[1:], target)
    # If first element is a list, descend into it to count within it,
    #    and continue with counts of remaining elements
    elif type(lst[0]) == list:
        return count(lst[0], target) + count(lst[1:], target)
    else:
        return 0 + count(lst[1:], target)
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