作者sean72 (.)
看板Python
标题Re: [问题] if 'string' not in i:
时间Sat Aug 24 11:12:48 2013
※ 引述《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
1F:推 nypgand1:因为前面被remove吧 08/24 11:25
2F:→ darkgerm:for 在跑时不要去改被 iterate 的值,不然会有问题 08/24 11:49
3F:→ darkgerm:原PO想做的事可以用 filter() 或 list-comprehension 做 08/24 11:52
4F:→ darkgerm:1. a = filter(lambda x: '/' in x, a) 08/24 11:53
5F:→ darkgerm:2. [i for i in a if '/' in i] 08/24 11:53
6F:推 vagic:推楼上 08/24 11:58
7F:→ pcyu16: ^ not 08/24 13:08