new_list = ["H1","H2",1999] for each_list in new_list: print (each_list);
若列表中包含嵌套列表,怎樣處理?spa
笨方法:判斷列表中元素是否是列表;並繼續使用for來循環打印, 缺點:多個嵌套列表時會使代碼過長太重複 難讀.net
1 new_list = ["H1","H2",1999,["hello","day"]] 2 3 for each_list in new_list: 4 if isinstance(each_list,list): 5 for new_each in each_list: 6 print (new_each) 7 else: 8 print (each_list);
若是想遇到列表就縮進一次怎麼辦?code
增長一個形參唄;blog
1 def each_list(list_name,level=0): 2 for yuansu in list_name: 3 if isinstance(yuansu,list): #判斷當前元素是否是列表 4 each_list(yuansu,level+1) #如是,則遞歸調用,而且標記當前元素是列表 5 else: 6 for tab in range(level):#固定次數 7 print ("\t",end='') 8 print (yuansu) 9 10 11 new_list = ["H1","H2",1999,["hello","day",["one","two"]]] 12 13 each_list(new_list)
若是加入一個開啓機制,不想加縮進&想加縮進 怎麼辦;遞歸
再次加入一個形參控制get
1 def each_list(list_name,count=False,level=0): #加入控制形參 count 默認爲不開啓縮進 2 for yuansu in list_name: 3 if isinstance(yuansu,list): #判斷當前元素是否是列表 4 each_list(yuansu,count,level+1) #如是,則遞歸調用,而且標記當前元素是列表 5 else: 6 if count: #判斷是否開啓縮進 7 for tab in range(level):#固定次數 8 print ("\t",end='') 9 print (yuansu) 10 else: 11 print (yuansu) 12 13 14 new_list = ["H1","H2",1999,["hello","day",["one","two"]]] 15 16 each_list(new_list)