溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python嵌套列表的方法

發(fā)布時間:2020-08-01 10:48:06 來源:億速云 閱讀:424 作者:清晨 欄目:編程語言

不懂python嵌套列表的方法?其實想解決這個問題也不難,下面讓小編帶著大家一起學(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()

運行,輸出為:

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]

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享python嵌套列表的方法內(nèi)容對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,遇到問題就找億速云,詳細(xì)的解決方法等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI