Recursively counting occurrences in a nested list of numbers

假装没事ソ 提交于 2019-12-13 16:26:53

问题


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)


来源:https://stackoverflow.com/questions/35448323/recursively-counting-occurrences-in-a-nested-list-of-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!