Re: [問題] not in 檢查list元素會失敗嗎?

作者: abc2090614 (casperxdd)   2018-12-26 11:42:44
※ 引述《ofspring (青春無敵)》之銘言:
: 我想做兩個list_A, list_B 元素的確認
: 然後用 list_A.remove() 移除掉不在list_B
: 最後的目標是讓list_A, list_B 相同
: 我的程式碼如下
: (python ver 3.6.6, MacOS, 用colab和jupyter notebook跑都是一樣的結果)
原因就跟推文說的一樣
在for裡面的位置被移動了
把 code 加上一點東西印出來
list_A = ["a", "b", "c","g", "f", "K", "larry", "curly", "moe"]
list_B = ["a", "b", "c","g", "f", "K"]
for index, element in enumerate(list_A):
print(index, element)
if element not in list_B:
list_A.remove(element)
得到的結果是
0 a
1 b
2 c
3 g
4 f
5 K
6 larry
7 moe
也就是在6移掉 "larry" 之後, 在7的位置變成 moe 所以剩一個curly
一般在兩個 list 切來切去會直接創一個新 list 而不會用.remove
https://twitter.com/raymondh/status/1055478808793546752
@raymondh
Q. What are the best practices for modifying a list while looping over it?
A. Don't.
Seriously, just make a new list and avoid hard-to-read code with hard-to-find
bugs.
我應該會這樣寫
new_list = [_ for _ in list_A if _ in list_B]
作者: ofspring (青春無敵)   2018-12-26 18:06:00
"Don't." XD 你的解法更直觀更快!剛剛CD無法按推文,解法漂亮補推一個

Links booklink

Contact Us: admin [ a t ] ucptt.com