1. Use the For loop first.
forIteminchL:ifisinstance (item, list): forNewIteminchItem:Print(NewItem)Else: Print(Item output:123456#With a for loop value, there are several layers of nesting to write a few layers for the loop, otherwise it will not be recognized. l=[1,2,[3,4],[5,6,[7,8]]] forIteminchL:ifisinstance (item, list): forNewIteminchItem:Print(NewItem)Else: Print(Item output:123456[7, 8]
2. Recursive function implementation:
recursive function implementation: def GetItem (L): for inch L: if isinstance (item,list): getitem (item) Else: Print (item) getitem (l) output:12345678910
Variable 1: It is indented once when the class table is encountered:
def getitem (l,level=0):
For item in L:
If Isinstance (item,list):
GetItem (item,level+1)
Else
For tab in range:
Print (' \ t ', end= ' #输出一个 tab, and remove the newline character after print, which is the indentation
Print (item)
GetItem (L)
Output:
Variable 2: Join the open mechanism, whether indent
def getitem (L,level=0,count=false):
For item in L:
If Isinstance (item,list):
GetItem (Item,level+1,count)
Else
If Count:
For tab in range:
Print (' \ t ', end= ' #输出一个 tab, and remove the newline character after print, which is the indentation
Print (item)
Print (item)
GetItem (L)
Output:
1
2
3
4
5
6
7
8
9
10
Python uses recursive functions to output each element of a nested list