应用一:遍历嵌套列表
方法一:for循环遍历嵌套列表
lists = ["m1", 1900, ["m2", 2000, ["m3", 2100]]]
for item_outer in lists:
if isinstance(item_outer, list):
for item_medium in item_outer:
if isinstance(item_medium, list):
for item_inner in item_medium:
print(item_inner)
else:
print(item_medium)
else:
print(item_outer)
方法二:定义函数递归遍历嵌套列表
注:Python3默认递归深度不超过100
def traverse_list(alist):
for each_item in alist:
if isinstance(each_item, list):
traverse_list(each_item)
else:
print(each_item)
lists = ["m1", 1900, ["m2", 2000, ["m3", 2100]]]
traverse_list(lists)