Python-读取嵌套列表中的字符串

问题:读取movies = ['a','b',['c','d',['f','g','h']]]里的每个字符串

方法:利用isinstance、for和if...else读取列表里的字符串。

具体步骤:

z =0
k = 0
q = 0
movies = ['a','b',['c','d',['f','g','h']]]
for each_item in movies:
    if isinstance(each_item,list)==False:
        print(each_item)
        z = z +1
    else:
        for p in each_item:
            if isinstance(p,list)==False:
                print(movies[z][k])
                k = k+1
            else:
                for s in p:
                    print(movies[z][k][q])
                    q=q+1

结果:
可是解决问题

存在问题:
如果嵌套级别太多,就要重复使用for和if...else,不断增加变量。

进一步优化:

movies = ['a','b',['c','d',['f','g','h']]]
for each_item in movies:
    if isinstance(each_item,list):
        for nested_item in each_item:
            if (nested_item, list) == False:
                print(nested_item)
            else:
                for f in nested_item:
                    print(f)
    else:
        print(each_item)

或者

movies = ['a','b',['c','d',['f','g','h']]]
for each_item in movies:
    if isinstance(each_item,list):
        for nested_item in each_item:
            if isinstance(nested_item, list) :
                for deeper_item in nested_item:
                    print(deeper_item)
            else:
                 print(nested_item)
    else:
        print(each_item)

总结:代码更少,清晰,但还存在一个问题:如果有更多的嵌套,该如何解决。
比如说movies = ['a','b',['c','d',['f','g','h',['o']]]]

使用函数,继续优化形成最终大法:

movies = ['a','b',['c','d',['f','g','h',['o']]]]
def item (name):
    for each_item in name:
        if isinstance(each_item,list):
            item(each_item)
        else:
            print(each_item)
print(item(movies))

这样,再也不怕嵌套的级别了。

问题解决方法参考了《Head First Python(中文版)》

你可能感兴趣的:(Python-读取嵌套列表中的字符串)