How to deal with deep nested Python list

来源:互联网 发布:商陆花软件是什么 编辑:程序博客网 时间:2024/06/03 16:26

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?

  1. 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 = 0lst=["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)

这里写图片描述

原创粉丝点击