久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Python通過(guò)遞歸函數(shù)輸出嵌套列表元素

瀏覽:4日期:2022-07-08 10:23:54

1.先用 for 循環(huán)取

for item in l: if isinstance(item ,list): for newitem in item: print(newitem) else: print(item

輸出:123456

#利用 for 循環(huán)取值,有幾層嵌套就要寫(xiě)幾層 for 循環(huán),否則不識(shí)別。l=[1,2,[3,4],[5,6,[7,8]]]for item in l: if isinstance(item ,list): for newitem in item: print(newitem) else: print(item

輸出

123456[7, 8]

2.遞歸函數(shù)實(shí)現(xiàn):

遞歸函數(shù)實(shí)現(xiàn):

def getitem(l): for item in l: if isinstance(item,list): getitem(item) else: print(item)getitem(l)

輸出:12345678910

變式1:遇到類(lèi)表就縮進(jìn)一次:

def getitem(l,level=0): for item in l: if isinstance(item,list): getitem(item,level+1) else: for tab in range(level):print(’t’,end=’’ #輸出一個(gè) 制表符,并且將 print 后面的換行符去掉,這樣就是了縮進(jìn) print(item)getitem(l)

輸出

Python通過(guò)遞歸函數(shù)輸出嵌套列表元素

變式2:加入開(kāi)啟機(jī)制,是否縮進(jìn)

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(level): print(’t’,end=’’ #輸出一個(gè) 制表符,并且將 print 后面的換行符去掉,這樣就是了縮進(jìn)print(item) print(item)getitem(l)

輸出

12345678910

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 永靖县| 乌兰浩特市| 绥德县| 枣庄市| 安仁县| 抚松县| 葵青区| 天等县| 定陶县| 虹口区| 定州市| 临邑县| 四平市| 赤水市| 成都市| 阜阳市| 长丰县| 玛纳斯县| 和田市| 怀集县| 扶余县| 浦东新区| 汝城县| 韶关市| 云霄县| 察隅县| 浦城县| 仁化县| 灵台县| 商水县| 乌苏市| 兖州市| 长治市| 湘潭市| 灵台县| 南投市| 凤城市| 辉南县| 无极县| 多伦县| 图们市|