作者yrabes (亞貝絲)
看板Python
標題[問題] for迴圈的串列表示
時間Thu Feb 24 11:34:59 2022
最近在練習使用for 迴圈 想比較兩串列並刪除重複元素
test1 = [1,2,3,5,7]
test2 = [1,2,3,4,5,6,7,8,9]
for x in
test2:
if x in test1:
test2.remove(x)
print("已刪除",x)
print(test2)
有問題的是黃色字的部分
如果是test2 會輸出 [2,4,6,8,9]
但如果改成 test2[:] 則會輸出[4,6,8,9] 少了2(也是我期望的)
請問為什麼會有不同
應該不管加不加[:] test2的每個元素都會跑過一遍才是
感謝回答~
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.83.72.172 (臺灣)
※ 文章網址: https://webptt.com/m.aspx?n=bbs/Python/M.1645673701.A.819.html
1F:推 robert09080: 這不是一個很好的寫法,因為你使用t2做迴圈,又刪除 02/24 11:57
2F:→ robert09080: t2中的元素 02/24 11:57
3F:→ robert09080: 請用 list comprehensive,[x for x in t2 if x no 02/24 11:58
4F:→ robert09080: t in t1] 02/24 11:58
5F:→ robert09080: 或是可以使用set,set(t2)-set(t1) 02/24 12:00
6F:→ yrabes: 喔喔 我懂您的意思了!!感謝您~ 02/24 12:08
7F:推 LeFilsDuVent: 至於為什麼會得到那個結果,test2[:]會是test2的一 02/24 15:30
8F:→ LeFilsDuVent: shallow copy,所以你的loop的確會跑遍x=1,2,...,9 02/24 15:31
9F:→ LeFilsDuVent: 但如果用for x in test2:那會跑的是x=1,3,5,7,9原因 02/24 15:32
10F:→ LeFilsDuVent: 就如同樓上解釋的,你在loop through test2同時又修 02/24 15:32
11F:→ LeFilsDuVent: 改test2 02/24 15:32
12F:→ yrabes: 感謝,這樣說我更清楚了!! 02/24 15:55