[問題] if 'string' not in i:

看板Python作者 (.)時間12年前 (2013/08/24 02:45), 編輯推噓0(004)
留言4則, 3人參與, 最新討論串1/6 (看更多)
#Python 3.3 a = ['a','b','c','d','x/'] for i in a: if '/' not in i: a.remove(i) print(a) 預期輸出: ['x/'] 實際輸出: ['b', 'd', 'x/'] 為什麼 b 和 d 兩個元素無法被濾掉? 雖然可以反向繞路 但還是非常疑惑 tmp = [] for i in a: if '/' in i: tmp.append(i) print(tmp) 感謝幫忙 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 172.249.127.149 ※ 編輯: sean72 來自: 172.249.127.149 (08/24 10:46)

08/24 10:54, , 1F
可以看一下for實際跑了些什麼
08/24 10:54, 1F
a = ['a','b','c','d','x'] for i in a: print(i) 印出 a b c d x # good == for i in a: print(i) if 'x' not in i: a.remove(i) print(a) 印出 a c x ['b', 'd', 'x'] #for迴圈把'b' 'd' 吃掉了?! ※ 編輯: sean72 來自: 172.249.127.149 (08/24 11:05)

08/24 11:02, , 2F
他實際上只有跑3次 你把i print 出來就知道了
08/24 11:02, 2F

08/24 11:03, , 3F
a c x/ 所以b d 沒有remove掉
08/24 11:03, 3F

08/24 11:06, , 4F
請問為什麼 b d 不會被for迴圈執行到呢?
08/24 11:06, 4F
a = ['1','2','3','4','5','6','7','8','x'] for i in a: print(i) if 'x' not in i: a.remove(i) print(a) Console: 1 3 5 7 x ['2', '4', '6', '8', 'x'] 為什麼只有奇數單位被for 執行到呢? ※ 編輯: sean72 來自: 172.249.127.149 (08/24 11:11)
文章代碼(AID): #1I61vTej (Python)
討論串 (同標題文章)
文章代碼(AID): #1I61vTej (Python)