作者ofspring (青春無敵)
看板Python
標題[問題] not in 檢查list元素會失敗嗎?
時間Tue Dec 25 23:41:40 2018
我想做兩個list_A, list_B 元素的確認
然後用 list_A.remove() 移除掉不在list_B
最後的目標是讓list_A, list_B 相同
我的程式碼如下
(python ver 3.6.6, MacOS, 用colab和jupyter notebook跑都是一樣的結果)
--
list_A = ["a", "b", "c","g", "f", "K", "larry", "curly", "moe"]
list_B = ["a", "b", "c","g", "f", "K"]
for element in list_A:
if element not in list_B:
list_A.remove(element)
print(list_A)
--
我得到的結果
['a', 'b', 'c', 'g', 'f', 'K', 'curly']
多了一個'curly' @@
想請教板上的高手們,是語法還是哪邊出錯呢?
1. not in 無法這樣使用?
2. remove()的問題?
(把元素換成數字也是有類似的狀況)
有嘗試把下面的這段獨立成一個cell, 執行第二次就完全相同了~
('curly'就成功remove)
--
for element in list_A:
if element not in list_B:
list_A.remove(element)
--
找了stackoverflow一個下午,找不到解答
我該使用哪些關鍵字呢?
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.135.86.153
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1545752503.A.36A.html
※ 編輯: ofspring (220.135.86.153), 12/25/2018 23:43:18
→ Luluemiko: 因為element被移動了,可是index並沒有跟著動 12/26 00:00
→ Luluemiko: 直觀作法就在迴圈前面加一個list的copy(),修改它就好 12/26 00:08
推 germun: 如果元素不重覆用set就好, 除非你只是想試試not in 12/26 00:39
推 iphone2003: 1. not in沒用錯,2.remove也沒錯,問題是出在你正在 12/26 03:34
→ iphone2003: 迭代的list_A會在迴圈中被改變,這個應該要儘量避免 12/26 03:34
→ iphone2003: 不過推樓上,用set應該最方便 12/26 03:34
推 yangs0618: 請問用set是什麼意思 要達到樓主要的功能怎麼用 12/26 07:33
→ toy9986619: 集合(set) 12/26 08:59
推 Yshuan: List known issue 很多語言都有這問題 12/26 09:07
推 yangs0618: 我知道set XD 是不知道怎麼在這個例子上用 12/26 10:47
推 XperiaZ6C: 在list_A.remove(element)之後把list A跟B都print出來 12/26 11:46
→ XperiaZ6C: 就知道問題在哪了 12/26 11:46
→ ofspring: 感謝各位高手的回覆 我用一個新的list就OK了 12/26 18:03
→ ofspring: set的解法感覺更優雅了 ~ thanks a lot 12/26 18:04
推 iphone2003: 補個set的作法,取交集就好 12/27 01:55
→ iphone2003: set(list_A) & set(list_B) 12/27 01:55