Python-正確刪除列表中的指定列表


title: Python-刪除列表中的列表
date: 2020-09-14 22:12:14
tags: Python采坑記


假設(shè)這樣一個(gè)場(chǎng)景,有一個(gè)列表 total_list, 里面包含的三個(gè)元素都是列表,分別是 l1, l2l3, 假設(shè)現(xiàn)在給定其中的一個(gè)元素,比如 l1, 要從 total_list 中刪除它。第一時(shí)間想到的會(huì)是使用下面的語(yǔ)句 total_list.remove(l1),乍一看很合情合理。并且通過(guò)下面的測(cè)試語(yǔ)句也可正常運(yùn)行

In [1]: l1 = [1, 2]

In [2]: l2 = [3, 4]

In [3]: l3 = [5, 6]

In [4]: total_list = [l1, l2,  l3]

In [5]: print(total_list)
[[1, 2], [3, 4], [5, 6]]

In [6]: total_list.remove(l1)

In [7]: print(total_list) # 正常刪除 l1
[[3, 4], [5, 6]]

In [8]: total_list.remove(l2)

In [9]: print(total_list) # 正常刪除 l2
[[5, 6]]

In [10]: total_list.remove(l3)

In [11]: print(total_list) # 正常刪除 l3
[]

不知各位有沒(méi)有看出什么異常,如果看不出的話,不妨看下下面的另一個(gè)測(cè)試?yán)?/p>

In [1]: l1 = []

In [2]: l2 = []

In [3]: l3 = []

In [4]: total_list = [l1, l2, l3]

In [5]: id(l1), id(l2), id(l3)
Out[5]: (140110036119496, 140110036107848, 140110036127368)

In [6]: total_list.remove(l3)

In [7]: print(total_list) # 可以看出 total_list 的列表確實(shí)少了一個(gè)
[[], []]

In [8]: l3.append(1) # 按照設(shè)想,l3 此時(shí)已不在 total_list 中,往 l3 中添加內(nèi)容,應(yīng)該不影響 total_list

In [9]: print(total_list) # 可以看出 total_list 改變了, l3 還在 total_list 中
[[], [1]]


In [11]: id(total_list[0]), id(total_list[1]) # 查看 id, 發(fā)現(xiàn) l2 和 l3 還在 total_list 中,被刪除的其實(shí)是 l1 !
Out[11]: (140110036107848, 140110036127368)

可以看出,我們希望刪除的是 l3, 但是實(shí)際上刪除的卻是 l1

原因在于在遍歷 total_list 時(shí), 遍歷到的第一個(gè)元素是 l1 時(shí), 滿足 __eq__ 方法, 所以此時(shí)直接把 l1total_list 中刪除。

Python 官方文檔的解釋如下

list.remove(x)
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.

那么,假設(shè)我現(xiàn)在就想刪除列表l3,可以使用如下函數(shù)

def remove_list(total_list, search_list):
     for i, _list in enumerate(total_list):
         if _list is search_list:
             del total_list[i]
             break

測(cè)試?yán)尤缦?/p>

In [1]: l1, l2, l3 = [], [], []

In [2]: id(l1), id(l2), id(l3)
Out[2]: (140163609930568, 140163610222216, 140163609929224)

In [3]: total_list = [l1, l2, l3]

In [4]: def remove_list(total_list, search_list):
   ...:     for i, _list in enumerate(total_list):
   ...:         if _list is search_list:
   ...:             del total_list[i]
   ...:             break
   ...:

In [5]: remove_list(total_list, l3)

In [6]: total_list
Out[6]: [[], []]

In [7]: l3.append(1)

In [8]: total_list
Out[8]: [[], []]

In [9]: id(total_list[0]), id(total_list[1])
Out[9]: (140163609930568, 140163610222216)

In [10]: 

可以看出 l3 已經(jīng)從 total_list 中刪除了

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容