奇怪的事情发生在这个代码:为什么'。'在'.remove'后生存?
fh = open('romeo.txt', 'r')
lst = list()
for line in fh:
line = line.split()
for word in line:
lst.append(word)
for word in lst:
numberofwords = lst.count(word)
if numberofwords > 1:
lst.remove(word)
lst.sort()
print len(lst)
print lst
romeo.txt从http://www.pythonlearn.com/code/romeo.txt
结果采取:
27
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'the', 'through', 'what', 'window', 'with', 'yonder']
正如你可以看到,有两个 '的'。这是为什么?这段代码运行它删除其余“的”,但为何它没有工作的第一次第二次后
for word in lst:
numberofwords = lst.count(word)
if numberofwords > 1:
lst.remove(word)
:我可以再次运行这部分代码?
正确的输出:
26
['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']
dunnno为什么它被编辑你现在需要滚动才能看到结果 – Gunnm
我的猜测是在'.remove()'之后,'for'循环没有正确循环(因为它可能无法正确地对元素进行索引)。 –
迭代时修改列表可能会导致未定义的行为。 –