→ djshen:可以看一下for實際跑了些什麼 08/24 10:54
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)
→ yume190:他實際上只有跑3次 你把i print 出來就知道了 08/24 11:02
→ yume190:a c x/ 所以b d 沒有remove掉 08/24 11:03
→ sean72:請問為什麼 b d 不會被for迴圈執行到呢? 08/24 11:06
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)