在这个代码中发生了一些奇怪的事情:
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 lstromeo.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']正如你所看到的,有两个“the”。为什么会这样呢?我可以再次运行这部分代码:
for word in lst:
numberofwords = lst.count(word)
if numberofwords > 1:
lst.remove(word)在第二次运行此代码之后,它会删除其余的“the”,但是为什么它第一次不能工作呢?
正确输出:
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']发布于 2015-07-11 11:13:17
在这个循环中:
for word in lst:
numberofwords = lst.count(word)
if numberofwords > 1:
lst.remove(word)lst是在迭代它时被修改的。别干那事。一个简单的解决方法是迭代它的副本:
for word in lst[:]:发布于 2015-07-11 11:25:12
Python提供了非常好的工具来使这类任务变得非常简单。通过使用内置的内容,您通常可以避免使用显式循环和就地修改循环变量所遇到的问题:
with open('romeo.txt', 'r') as fh:
words = sorted(set(fh.read().replace('\n', ' ').split(' ')))
print(len(words))
print(words)https://stackoverflow.com/questions/31356546
复制相似问题