我不明白为什么我的代码不能正常工作。我试图从一个列表中移除长度只有一个字符的单词:
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']
有人可以解释一下为什么这个不正常工作并且如何修复吗?
我不明白为什么我的代码不能正常工作。我试图从一个列表中移除长度只有一个字符的单词:
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']
有人可以解释一下为什么这个不正常工作并且如何修复吗?
按照以下步骤进行:
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