1. 程式人生 > >Python列印多層巢狀列表

Python列印多層巢狀列表

列表中巢狀列表
遞迴呼叫,將列表幾巢狀中的列表元素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]