python中l(wèi)ist能不能嵌套-創(chuàng)新互聯(lián)

創(chuàng)新互聯(lián)www.cdcxhl.cn八線動態(tài)BGP香港云服務(wù)器提供商,新人活動買多久送多久,劃算不套路!

創(chuàng)新互聯(lián)公司是由多位在大型網(wǎng)絡(luò)公司、廣告設(shè)計公司的優(yōu)秀設(shè)計人員和策劃人員組成的一個具有豐富經(jīng)驗的團隊,其中包括網(wǎng)站策劃、網(wǎng)頁美工、網(wǎng)站程序員、網(wǎng)頁設(shè)計師、平面廣告設(shè)計師、網(wǎng)絡(luò)營銷人員及形象策劃。承接:網(wǎng)站設(shè)計制作、成都網(wǎng)站制作、網(wǎng)站改版、網(wǎng)頁設(shè)計制作、網(wǎng)站建設(shè)與維護、網(wǎng)絡(luò)推廣、數(shù)據(jù)庫開發(fā),以高性價比制作企業(yè)網(wǎng)站、行業(yè)門戶平臺等全方位的服務(wù)。

小編給大家分享一下python中l(wèi)ist能不能嵌套,相信大部分人都還不怎么了解,因此分享這篇文章給大家學(xué)習(xí),希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去學(xué)習(xí)方法吧!

python中的列表是可以嵌套的。將嵌套的list遍歷并輸出是很常見的需求。以下通過兩種方法達到目的

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()

讓代碼run起來,輸出為:

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ì)上也是遞歸的思路。

推薦學(xué)習(xí)《python教程》

2.兩層嵌套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)

讓代碼run起來:

[1, 2, 3, 4, 5, 6, 7]

基本思路:將每一個子list轉(zhuǎn)為set,然后求并集,即可。

3.多重嵌套去重

def dup_remove(list_raw,result):
    for item in list_raw:
        if isinstance(item, list):
            dup_remove(item,result)
        else:
            result.add(item)
    return  list(result)
def main():   
    list_raw = ["a",["b","c",["d","a","b"]]]
    result = set()
    print "dup_remove is:  ",dup_remove(list_raw,result)

讓代碼run起來:

dup_remove is:   ['a', 'c', 'b', 'd']

基本思路與之前遍歷嵌套list的思路差不多,唯一的區(qū)別就是之前result是一個list,而要去重的話用result是一個set,保證最后的結(jié)果為去重的結(jié)果。

以上是python中l(wèi)ist能不能嵌套的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)-成都網(wǎng)站建設(shè)公司行業(yè)資訊頻道!

當(dāng)前名稱:python中l(wèi)ist能不能嵌套-創(chuàng)新互聯(lián)
轉(zhuǎn)載來源:http://bm7419.com/article0/gocoo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供關(guān)鍵詞優(yōu)化、Google建站公司、網(wǎng)站建設(shè)虛擬主機、企業(yè)網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站優(yōu)化排名