Re: [問題] not in 檢查list元素會失敗嗎?
※ 引述《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]
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 68.71.180.136
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1545795767.A.EB8.html
→
12/26 18:06,
5年前
, 1F
12/26 18:06, 1F
推
12/26 18:11,
5年前
, 2F
12/26 18:11, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):