作者sean72 (.)
看板Python
标题[问题] if 'string' not in i:
时间Sat Aug 24 10:45:47 2013
#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)
1F:→ 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)
2F:→ yume190:他实际上只有跑3次 你把i print 出来就知道了 08/24 11:02
3F:→ yume190:a c x/ 所以b d 没有remove掉 08/24 11:03
4F:→ 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)