Recursively counting occurrences in a nested list

2019-08-08 21:31发布

问题:

I'm finally getting around to recursion in Python and trying to count the number of occurrences of a target number in a list. However, I'm running into issues with counting occurrences in a nested list of numbers.

For example

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)

Output

>>> count( [1,2,3,[4,5,5],[[5,2,1],4,5],[3]], 1 )

Output: 1

Expected output: 2

Is there an easy way to flatten nested-lists in Python? Or a simple way for me to account for the fact that there is a nested-list in my code?

回答1:

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


回答2:

You just need an extra case to deal with lst[0] being a sublist, like:

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)