python二維列表遍歷刪除


for循環遍歷的是一開始的列表,每次都會找列表中的第i個元素

card_list = [['wong', '1', '1'], ['ben', '1', '1'], ['zhuzhu', '1', '1'], ['nannan', '1', '1']]

for card in card_list:
    index = card_list.index(card)
    del card_list[index]

print(card_list)

結果:[['ben', '1', '1'], ['nannan', '1', '1']]

原因:for遍歷列表是一開始索引下標為0-3的,逐漸減少數據,列表並沒有更新。
所以在刪除索引為0數據后,ben的索引變成了0,zhuzhu索引為1,按照遍歷就去刪除了索引為1的數據。

解決這個問題:
方法1:用while循環

i = 0
while i < len(card_list):
    for card in card_list:
        index = card_list.index(card)
        del card_list[index]

方法2:切片

for card in card_list[ : ]:
    index = card_list.index(card)
    del card_list[index]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM