python如何嵌套列表
python中的列表是可以嵌套的。將嵌套的list遍歷并輸出是很常見的需求。以下通過兩種方法達到目的
defnested_list(list_raw,result):
foriteminlist_raw:
ifisinstance(item,list):
nested_list(item,result)
else:
result.append(item)
returnresult
defflatten_list(nested):
ifisinstance(nested,list):
forsublistinnested:
foriteminflatten_list(sublist):
yielditem
else:
yieldnested
defmain():
list_raw=["a",["b","c",["d"]]]
result=[]
print"nested_listis:",nested_list(list_raw,result)
print"flatten_listis:",list(flatten_list(list_raw))
main()
運行,輸出為:
nested_listis:['a','b','c','d']
flatten_listis:['a','b','c','d']
nested_list方法采用遞歸的方式,如果item是list類型,繼續遞歸調用自身。如果不是,將item加入結果列表中即可。
flatten_list方法則是采用生成器的方式,本質上也是遞歸的思路。
兩層嵌套list去重
list里面套了一層list,需要去重,并在生成一個去重的list。請看代碼:
defdup_remove_set(list_raw):
result=set()
forsublistinlist_raw:
item=set(sublist)
result=result.union(item)
returnlist(result)
defmain():
list_dup=[[1,2,3],[1,2,4,5],[5,6,7]]
printdup_remove_set(list_dup)
運行
[1,2,3,4,5,6,7]
以上內容為大家介紹了python如何嵌套列表,希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。

相關推薦HOT
更多>>
如何使用Pandas處理Excel?
如何使用Pandas處理Excel?做過行政或者人事,或者對此有過了解的小伙伴,一定對下發各個部分的表有著非常深刻的印象,最常見的就是需要我們將一...詳情>>
2023-11-14 07:43:15
python中np.insert()函數的使用方法
python中np.insert()函數的使用方法在numpy數組操作中,np.append()方法可以在每行每列的最后添加數據,但其位置是規定的,那如果想要指定添加...詳情>>
2023-11-14 05:06:13
SVM在python中的原理如何理解?
SVM在python中的原理如何理解?在python中除了編程化的知識點外,對于數學方法的算法也有所涉及,SVM就是一種很好地體現。我們學習過數學中的坐...詳情>>
2023-11-14 04:30:04
python處理絕對路徑和相對路徑函數有哪些?
python處理絕對路徑和相對路徑函數有哪些?絕對路徑和相對路徑是什么?絕對路徑:從根文件夾開始,Windows系統以盤符(C:)作為根文件夾,OSX或Lin...詳情>>
2023-11-14 03:33:02熱門推薦
如何使用python any()判斷多元素?
沸如何使用Pandas處理Excel?
熱python函數中的參數有哪些?
熱python中pygal模塊如何使用?
新Python的excel處理操作
python中doctest庫是什么?
python中series是什么意思
python中np.insert()函數的使用方法
SVM在python中的原理如何理解?
Python描述符中有哪三種方法?
python處理絕對路徑和相對路徑函數有哪些?
python單繼承和多繼承如何定義?
python封裝中的私有如何理解?
python模塊引入的三種方式
技術干貨






