[問題] 刪除list中特定的element

看板Python作者 (明月照大江)時間11年前 (2014/02/02 17:48), 編輯推噓2(207)
留言9則, 4人參與, 最新討論串1/3 (看更多)
小弟有個問題請各位大師,我想要刪掉input list中特定的element 以下為例,想要刪掉值為0,9 的element。但是index=7的0 刪不掉。 請問程式碼哪裡出錯造成這樣的問題? 謝謝各位撥冗解救小弟 ================================ input = [0,0,1,2,3,4,0,5,6,7,8] del_char = [0,9] print input for item in input: if item in del_char: input.remove(item) print input ================================ 預期結果:[1,2,3,4,5,6,7,8] 實際結果:[1,2,3,4,0,5,6,7,8] -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 27.241.199.95

02/02 18:25, , 1F
你在loop中不能把"input"改掉,會影響for loop的判斷
02/02 18:25, 1F

02/02 22:10, , 2F
話說input保留字喔
02/02 22:10, 2F

02/02 22:14, , 3F
感謝大師!
02/02 22:14, 3F

02/03 09:36, , 4F
問題在於你完全搞錯了list.remove的用法吧
02/03 09:36, 4F

02/03 09:41, , 5F
要用remove可以這樣寫
02/03 09:41, 5F

02/03 09:42, , 6F
for item in del_char:
02/03 09:42, 6F

02/03 09:42, , 7F
while(item in input):
02/03 09:42, 7F

02/03 09:43, , 8F
input.remove(item)
02/03 09:43, 8F

02/03 09:45, , 9F
阿while不用括弧
02/03 09:45, 9F
文章代碼(AID): #1IxXHRXT (Python)
文章代碼(AID): #1IxXHRXT (Python)