Python中删除了几个列表元素,同时在for循环中删除它们

时间:2015-11-16 00:22:36

标签: python

我想知道为什么在这个程序中没有删除某些元素的原因是什么。有人可以提供指针吗?

程序:

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。

3 个答案:

答案 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值的新列表。

如果partialoperator.ne的使用不符合您的喜好,您可以使用lambda

for n in filter(lambda x: x != '2', t):
    print('hello {}'.format(n))