递归计数嵌套数字列表中的出现次数 [英] Recursively counting occurrences in a nested list of numbers

查看:77
本文介绍了递归计数嵌套数字列表中的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我终于可以使用Python进行递归了,并试图计算list中目标数字的出现次数.但是,我在计数嵌套的list数字中出现的次数时遇到了问题.

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.

例如

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中展平嵌套列表?或者是一种简单的方法来说明我的代码中存在一个嵌套列表这一事实?

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?

推荐答案

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

这篇关于递归计数嵌套数字列表中的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆