Python uses recursive functions to output each element of a nested list

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.