这是一个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/