看板 Python 關於我們 聯絡資訊
我想應該是這樣 因為你邊執行loop邊remove 所以跑完第一次loop a會變成['2','3','4','5','6','7','8','x'] 然後接下來會從第二個element 也就是'3'開始跑 所以才會感覺只有執行到奇數 你可以在remove之後 print出a來看看 應該就比較明白:) ※ 引述《sean72 (.)》之銘言: : ※ 引述《sean72 (.)》之銘言: : : #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) : : 感謝幫忙 : 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 執行到呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 60.245.65.179
yoshien:感謝分享 08/25 20:43