看板 Python 關於我們 聯絡資訊
※ 引述《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: 172.249.127.149
nypgand1:因為前面被remove吧 08/24 11:25
darkgerm:for 在跑時不要去改被 iterate 的值,不然會有問題 08/24 11:49
darkgerm:原PO想做的事可以用 filter() 或 list-comprehension 做 08/24 11:52
darkgerm:1. a = filter(lambda x: '/' in x, a) 08/24 11:53
darkgerm:2. [i for i in a if '/' in i] 08/24 11:53
vagic:推樓上 08/24 11:58
pcyu16: ^ not 08/24 13:08