Python 从列表中删除单个字符

Python 从列表中删除单个字符,python,string,list,iteration,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','a','b','c','d','

我很难理解为什么我的代码无法工作。 我正在尝试从列表中删除长度仅为一个字符的单词:

line = ['word','a','b','c','d','e','f','g']
for words in line:
    if len(words) == 1:
        line.remove(words)
此代码返回以下内容(看起来会删除“每隔一个”单个字符):

有人能解释一下为什么不能正常工作以及如何修复吗?

执行以下操作:

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

非常常见的错误。不要在遍历列表时修改它。下面的答案提供了实现预期结果的正确方法
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