列表的嵌套

# Author kevin_hou
movies = ["The Holy Grail", 1975, "Terry Jones & Terry Gilliam",91,
          ["Graham Chapman",
           ["Michel Palin","John Cleese",
            "Terry Gilliam", "Eric Idle", "Terry Jones"]]]
print(movies)
'''
['The Holy Grail', 1975, 'Terry Jones & Terry Gilliam', 91, ['Graham Chapman', ['Michel Palin', 'John Cleese', 'Terry Gilliam', 'Eric Idle', 'Terry Jones']]]

'''

for each_item in movies:
    print(each_item)
'''
The Holy Grail
1975
Terry Jones & Terry Gilliam
91
['Graham Chapman', ['Michel Palin', 'John Cleese', 'Terry Gilliam', 'Eric Idle', 'Terry Jones']]

'''

for each_item in movies:
    if isinstance(each_item, list): #检查当前列表是否为一个列表
        for nested_item in each_item:   #内循环需要一个新的目标标识符
            print(nested_item)  #如果这是一个列表,使用另一个“for”循环处理这个嵌套列表
    else:
        print(each_item)    #如果外围列表的当前项不是一个列表,则在屏幕上显示这一项
'''
The Holy Grail
1975
Terry Jones & Terry Gilliam
91
Graham Chapman
['Michel Palin', 'John Cleese', 'Terry Gilliam', 'Eric Idle', 'Terry Jones']
'''
# help(isinstance(object,tuple))

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)

'''
The Holy Grail
1975
Terry Jones & Terry Gilliam
91
Graham Chapman
Michel Palin
John Cleese
Terry Gilliam
Eric Idle
Terry Jones
'''

  

posted @ 2020-09-01 23:08  JRS077  阅读(487)  评论(0编辑  收藏  举报