gpt4 book ai didi

python - 为什么 'the' 在 .remove 之后仍然存在?

转载 作者:太空狗 更新时间:2023-10-29 20:37:53 24 4
gpt4 key购买 nike

这段代码中发生了一些奇怪的事情:

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']

如您所见,有两个“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']

最佳答案

在这个循环中:

for word in lst:
numberofwords = lst.count(word)
if numberofwords > 1:
lst.remove(word)

lst 在迭代时被修改。不要那样做。一个简单的解决方法是迭代它的一个副本:

for word in lst[:]:

关于python - 为什么 'the' 在 .remove 之后仍然存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31356546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com