我无法理解为什么我的代码无法正常工作。我正在尝试从列表中删除仅一个字符的单词:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句