我想知道为什么在这个程序中没有删除某些元素的原因是什么。有人可以提供指针吗?
程序:
t = ['1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '7', '8', '9', '10']
print len(t)
for x in t:
if x == '2':
print x
t.remove(x)
else:
print 'hello: '+str(x)
print t
我的系统输出:
14
hello: 1
2
2
2
2
2
hello: 8
hello: 9
hello: 10
['1', '2', '2', '2', '2', '7', '8', '9', '10']
我使用的是Python 2.6.2。
答案 0 :(得分:3)
永远不要改变你要迭代的顺序。
@ cjonhson318的list-comprehension工作正常,或效率较低,但更接近于你的代码,只需在你改变列表本身时循环列表的副本:
for x in list(t):
if x == '2':
print x
t.remove(x)
else:
print 'hello: '+str(x)
正如您所看到的,代码中的唯一更改是循环list(t)
(t
的初始值的副本)而不是t
本身 - 这个适度的更改让您将t
本身改变到你内心的循环中。
答案 1 :(得分:1)
说出类似的话:
t = [ i for i in t if i != '2' ]
for item in t:
print "Hello "+item
答案 2 :(得分:1)
另一种方法是获得功能
from operator import ne
from functools import partial
t = ['1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '7', '8', '9', '10']
for n in filter(partial(ne, '2'), t):
print('hello {}'.format(n))
使用filter
功能创建一个减去2
值的新列表。
如果partial
和operator.ne
的使用不符合您的喜好,您可以使用lambda
for n in filter(lambda x: x != '2', t):
print('hello {}'.format(n))