python打印嵌套列表

# Author:Sooele

new_list = ["H1", "H2", 1999,"S",66]

for each_list in new_list:
    print(each_list);

若列表中包含嵌套列表,怎样处理?

笨方法:判断列表中元素是不是列表;并继续使用for来循环打印, 缺点:多个嵌套列表时会使代码过长过重复 难读

new_list = ["H1", "H2", 1999, ["hello", "day"]]

for each_list in new_list:
    if isinstance(each_list, list):
        for new_each in each_list:
            print(new_each)
    else:
        print(each_list);

简单方法:编写递归函数

def each_list(list_name):
    for yuansu in list_name:
        if isinstance(yuansu, list):
            each_list(yuansu)
        else:
            print(yuansu)


new_list = ["H1", "H2", 1999, ["hello", "day"], ["one", "two"]]

each_list(new_list)

如果想遇到列表就缩进一次怎么办?

增加一个形参呗;

def each_list(list_name, level=0):
    for yuansu in list_name:
        if isinstance(yuansu, list):  # 判断当前元素是不是列表
            each_list(yuansu, level + 1)  # 如是,则递归调用,并且标记当前元素是列表
        else:
            for tab in range(level):  # 固定次数
                print("\t", end='')
            print(yuansu)


new_list = ["H1", "H2", 1999, ["hello", "day", ["one", "two"]]]

each_list(new_list)

如果加入一个开启机制,不想加缩进&想加缩进 怎么办;

再次加入一个形参控制

def each_list(list_name, count=False, level=0):  # 加入控制形参 count 默认为不开启缩进
    for yuansu in list_name:
        if isinstance(yuansu, list):  # 判断当前元素是不是列表
            each_list(yuansu, count, level + 1)  # 如是,则递归调用,并且标记当前元素是列表
        else:
            if count:  # 判断是否开启缩进
                for tab in range(level):  # 固定次数
                    print("\t", end='')
                print(yuansu)
            else:
                print(yuansu)


new_list = ["H1", "H2", 1999, ["hello", "day", ["one", "two"]]]

each_list(new_list)