一个Python列表
movies = ["The Holy Grail",1975,"Terry Jones&Terry Gilliam",91,["Graham Chapman",["Michael Palin","John Cleesl","Terry Gillam","Eric Idle","Terry Jonse"]]]
一个电影列表分别是电影名,年,导演,分钟,主演,配角
列表又嵌套了其他列表
打印列表
>>> print movies
['The Holy Grail', 1975, 'Terry Jones&Terry Gilliam', 91, ['Graham Chapman', ['Michael Palin', 'John Cleesl', 'Terry Gillam', 'Eric Idle', 'Terry Jonse']]]
按列表内容分别打印
>>> for each_item in movies:
... print each_item
...
The Holy Grail
1975
Terry Jones&Terry Gilliam
91
['Graham Chapman', ['Michael Palin', 'John Cleesl', 'Terry Gillam', 'Eric Idle', 'Terry Jonse']]
对于最后一个嵌套列表没有分开打印
修改代码使用多重循环即可
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)
对于这种列表中的列表中的列表使用多重循环是可以分别打印出信息。增加一个for和if语句即可但是这样会很麻烦,可以定义一个递归函数实现这个功能
>>> def print_lol(the_list):
... for each_item in the_list:
... if isinstance(each_item,list):
... print_lol(each_item)
... else:
... print(each_item)
print_lol(movies)