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

时间:2016-02-17 05:04:42

标签: python python-3.x recursion nested-lists flatten

我终于在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中展平嵌套列表?或者我可以通过一种简单的方法来解释代码中存在嵌套列表这一事实?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

您只需要一个额外的案例来处理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)