从列表中删除单个字符

时间:2014-06-25 13:34:16

标签: python string list iteration

我无法理解为什么我的代码无法正常工作。 我试图从列表中删除长度只有一个字符的单词:

line = ['word','a','b','c','d','e','f','g']
for words in line:
    if len(words) == 1:
        line.remove(words)

此代码返回此代码(其中包含删除'其他所有'单个字符):

>>> line
['word', 'b', 'd', 'f']

任何人都可以解释为什么这不能正常工作以及如何解决?

1 个答案:

答案 0 :(得分:5)

这样做:

line = ['word','a','b','c','d','e','f','g']
line = [i for i in line if len(i) > 1]

您的代码存在的问题是您在迭代时从列表中删除哪个不安全。它将改变列表的长度:

line = ['word','a','b','c','d','e','f','g']
iterated = 0
removed = 0
for words in line:
    iterated += 1
    if len(words) == 1:
        line.remove(words)
        removed += 1

print line # ['word', 'b', 'd', 'f']
print iterated # 5
print removed # 4