python - 递归搜索多重嵌套列表并返回整数 : Python

标签 python recursion

这是一个Python程序。这是我到目前为止所拥有的。程序当前忽略多层嵌套列表,仅计算单层值。检查列表的方法必须是索引。

def DigitCount(lst):
    if len(lst)==0:
        return 0
    val = DigitCount(lst[1:])
    if len(lst) > 0:
        if type(lst[0]) != list:
            if type(lst[0]).isdigit():
                return 1 + val
        if type(lst[0])==list:
            DigitCount(lst[0])
            return val
    return val

最佳答案

您可以使用 sum 简化逻辑,递归调用 DigitCount(ele)列表元素或以其他方式检查元素是否int 并对所有结果求和:

def DigitCount(lst):
    return sum(DigitCount(ele) if isinstance(ele, list) else isinstance(ele, int) 
               for ele in lst)

输出:

In [22]: DigitCount([[1, 2, 3], [1, 2, 3, [4, 5, [3, 4, 3]]]])
Out[22]: 11

isinstance(ele, int) 返回 0 或 1,因此每个递归调用返回 1 或 0,因此这是对所有值求和的简单情况。

关于python - 递归搜索多重嵌套列表并返回整数 : Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35785349/

相关文章:

Java - 递归 2D boolean 数组方法上不应该发生的 StackOverflow 错误

javascript - javascript 中的递归回溯(闭包)

c - 返回后的函数 kepps(递归 C)

Python C API 性能提升?

python - 将 Django 模型对象转换为 dict 并且所有字段都完好无损

Python 运行时错误 : Failed to import pydot

python - 动态导入python模块

algorithm - 分析算法中的递归

performance - Scala 列表递归性能

python - tensorflow 错误: ValueError: None values not supported