去除多余嵌套的列表

题目

list1 = [11, [22, 3], [4, ], [55, 66], 8, [9, [7, [12, [34, [26]]]]]]

去除多余嵌套的列表,获得[11, 22, 3, 4, 55, 66, 8]app

解题

方法1:ide

def func(x):
    ret = []
    for b in x:
        if isinstance(b, list):
            for a in func(b):
                ret.append(a)
        else:
            ret.append(b)
    return ret

ret = func(list1)
print(ret)

方法2:列表推导式code

def func(x):
    return [a for b in x for a in func(b)] if isinstance(x, list) else [x]

ret = func(list1)
print(ret)
相关文章
相关标签/搜索