Gun*_*nnm 8 python string python-2.7 python-3.x
这段代码中发生了一些奇怪的事:
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
Run Code Online (Sandbox Code Playgroud)
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']
Run Code Online (Sandbox Code Playgroud)
如你所见,有两个'the'.这是为什么?我可以再次运行这部分代码:
for word in lst:
numberofwords = lst.count(word)
if numberofwords > 1:
lst.remove(word)
Run Code Online (Sandbox Code Playgroud)
在第二次运行此代码后,它会删除剩余的'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']
Run Code Online (Sandbox Code Playgroud)
Yu *_*Hao 14
在这个循环中:
for word in lst:
numberofwords = lst.count(word)
if numberofwords > 1:
lst.remove(word)
Run Code Online (Sandbox Code Playgroud)
lst迭代时修改它.不要那样做.一个简单的解决方法是迭代它的副本:
for word in lst[:]:
Run Code Online (Sandbox Code Playgroud)
Python提供了美味的工具,可以轻松完成这些任务.通过使用内置的东西,通常可以避免使用显式循环和现场修改循环变量时遇到的各种问题:
with open('romeo.txt', 'r') as fh:
words = sorted(set(fh.read().replace('\n', ' ').split(' ')))
print(len(words))
print(words)
Run Code Online (Sandbox Code Playgroud)