新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python如何嵌套列表
python中的列表是可以嵌套的。將嵌套的list遍歷并輸出是很常見的需求。以下通過兩種方法達到目的

成都創(chuàng)新互聯(lián)公司專注于網(wǎng)站建設,為客戶提供成都網(wǎng)站設計、成都網(wǎng)站建設、外貿(mào)網(wǎng)站建設、網(wǎng)頁設計開發(fā)服務,多年建網(wǎng)站服務經(jīng)驗,各類網(wǎng)站都可以開發(fā),成都品牌網(wǎng)站建設,公司官網(wǎng),公司展示網(wǎng)站,網(wǎng)站設計,建網(wǎng)站費用,建網(wǎng)站多少錢,價格優(yōu)惠,收費合理。
def nested_list(list_raw,result): for item in list_raw: if isinstance(item, list): nested_list(item,result) else: result.append(item) return result def flatten_list(nested): if isinstance(nested, list): for sublist in nested: for item in flatten_list(sublist): yield item else: yield nested def main(): list_raw = ["a",["b","c",["d"]]] result = [] print "nested_list is: ",nested_list(list_raw,result) print "flatten_list is: ",list(flatten_list(list_raw)) main()
運行,輸出為:
nested_list is: ['a', 'b', 'c', 'd'] flatten_list is: ['a', 'b', 'c', 'd']
nested_list方法采用遞歸的方式,如果item是list類型,繼續(xù)遞歸調(diào)用自身。如果不是,將item加入結(jié)果列表中即可。
flatten_list方法則是采用生成器的方式,本質(zhì)上也是遞歸的思路。
兩層嵌套list去重
list里面套了一層list,需要去重,并在生成一個去重的list。請看代碼:
def dup_remove_set(list_raw): result = set() for sublist in list_raw: item = set(sublist) result = result.union(item) return list(result) def main(): list_dup = [[1,2,3],[1,2,4,5],[5,6,7]] print dup_remove_set(list_dup)
運行
[1, 2, 3, 4, 5, 6, 7]
推薦學習《python教程》。
分享標題:創(chuàng)新互聯(lián)Python教程:python如何嵌套列表
當前URL:http://m.fisionsoft.com.cn/article/dhiogis.html


咨詢
建站咨詢
