递归 实例1

已知有列表:
L = [[3,5,8],10,[[13,14],15],18]
1)写出一个函数print_list(lst)打印出列表中所有数字
print_list(L)
2)写出一个函数sum_list(lst)返回列表中所有数字的和
print_list(sum_list(L))
注:
type(x) 可以返回一个变量的类型L = [[3,5,8],10,[[13,14],15],18]

def print_list(L): for x in L: if type(x) != list: #判断对应元素是一个列表还是数值,如果是数值直接打印 print(x,end=' ') else: #否则调用print_list()递归的将对应列表内元素进行打印 print_list(x) print_list(L) 执行结果: 3 5 8 10 13 14 15 18
def sum_list(lst):
    val = 0
    for x in lst:
        if type(x) != list:
            val += x
        else:
            val+=sum_list(x)
    return val

print(sum_list(L))
执行结果:
86

  

原文地址:https://www.cnblogs.com/vincent-sh/p/12543948.html