Python打印多层嵌套列表

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wang725/article/details/84673495

列表中嵌套列表
递归调用,将列表几嵌套中的列表元素append到一个新列表中

如下列表

[
    1, 
    2, 
    [
        3, 
        4, 
        [
            5, 
            6, 
            7
        ], 
        [
            8, 
            [
                9, 
                10
            ], 
            11
        ]
    ], 
    12, 
    [
        13, 
        14
    ]
]

上代码

lst = [1, 2, [3, 4, [5, 6, 7], [8, [9, 10], 11]], 12, [13, 14]]
    print '原多层嵌套列表:'
    print lst
    lst_new = []
    def get_lst_element(lst):
        for i in lst:
            if type(i) is list:
                get_lst_element(i)
            else:
                lst_new.append(i)
        return lst_new
    print '遍历打印该多层嵌套列表:'
    print get_lst_element(lst)

简化版

    # 简化版
    lst_new_simplify = []
    def get_lst_element_simplify(lst):
        for i in lst:
            get_lst_element_simplify(i) if type(i) is list else lst_new_simplify.append(i)
        return lst_new_simplify
    print '简化版遍历打印该多层嵌套列表again:'
    print get_lst_element_simplify(lst)

运行结果

原多层嵌套列表:
[1, 2, [3, 4, [5, 6, 7], [8, [9, 10], 11]], 12, [13, 14]]
遍历打印该多层嵌套列表:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
简化版遍历打印该多层嵌套列表again:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

猜你喜欢

转载自blog.csdn.net/wang725/article/details/84673495