python做题记录之list深度

题目描述:
给你一个多层list L, 如 L=[1,2,3,[4,[5,6]]], 求出最内层[]的深度并输出, 如样例L的结果为3
示例:
输入:L = [1, 2, 3, [4, [5, 6]]]

输出:3
定义一个新的list,将原list中的子list全部并排放入新list中,循环直到新的list没有子list

def sonlist(x):
    lst = []
    for y in x:
        if type(y) == list:
            for z in y:
                lst.append(z)
    return lst
new_lst = L
cnt = 0
while len(new_lst) > 0:
    cnt += 1
    new_lst = sonlist(new_lst)
print(cnt)

猜你喜欢

转载自blog.csdn.net/qq_53029299/article/details/114692944