一、
今天发现一个奇怪的现象,代码如下:
aList = ['xyz', 'zara', 'abc', 'xyz','xysdfji','xywooudd']
for x in aList:
if x.startswith('xy'):
aList.remove(x)
print "List : ", aList 输出如下=>发现没有最后一个元素也是以xy开头,但是没有删除掉
List : ['zara', 'abc', 'xysdfji']
二、换成如下的就可以了
aList = ['xyz', 'zara', 'abc', 'xyz','xysdfji','xywooudd']
for x in aList[:]:
if x.startswith('xy'):
aList.remove(x)
print "List : ", aList
输出如下=>发现没有最后一个元素也是以xy开头,但是没有删除掉
List : ['zara', 'abc']
三、比较它们两个的区别
aList = ['xyz', 'zara', 'abc', 'xyz','xysdfji','xywooudd']
print id(aList)
print id(aList[:])
print "------------"
for y in aList:
print y
print "----------"
for x in aList[:]:
输出如下=>
4534445984
4534446200
------------
xyz
zara
abc
xyz
xysdfji
xywooudd
----------
xyz
zara
abc
xyz
xysdfji
xywooudd