As the most common and basic data struct in Python , List is used in many situations , but when we meet deep nested List ,how we deal with it?
- For fewer nested python list we can combine if clause and isinstance()BIF to handle it as follow eg(two level nested list):
lst=["level1.2",["level2.1","level2.2"],"level1.3"]
for item in lst:
if isinstance(item, list):
for item1 in item:
print (item1)
else:
print (item)
2.For deeply nested list , absolutely you can add more if clause and isinstance()BIF to handle, but there is a problem: many levels if judgements and too much code makes it hard to understand the program, so we try another way: define a function then do a selfcall(recursion) to access the list
flag = 0
lst=["level1.2",["level2.1",["level2.21",["level2.211",["level2.211",["level2.211",["level2.211","level2.212"]]]]]],"level1.3"]
def deep_list(lst):
global flag
for item in lst:
if isinstance(item, list):
flag=flag+1
print ("list level:",flag,"start")
deep_list(item)
else:
print (item)
deep_list(lst)