简体   繁体   English

"ValueError : list.remove(x): x not in list" 当 x 在列表中时

[英]"ValueError : list.remove(x): x not in list" when x is in list

I have tried many possible solutions but none of them worked.我尝试了许多可能的解决方案,但没有一个奏效。 My code is a simple word counter that counts the frequency of words in song lyrics.我的代码是一个简单的单词计数器,用于计算歌词中单词的频率。 Since short words should't be counted I wrote this code.由于不应计算短词,因此我编写了此代码。 My word and their count lists look like this.我的单词和他们的计数列表看起来像这样。

 goodwords=["a", "my", "the", "I", "long", "up", "on"] 
 count=[26, 16, 16, 15, 12, 11, 11 ]

So I wrote this code to filter out short words.所以我写了这段代码来过滤掉短词。

for word in goodwords:
if len(word)<3:
        goodwords.index(word)
        count.remove(goodwords.index(word))
        goodwords.remove(word)

        

Python throws me this error: Python 向我抛出此错误:

ValueError: list.remove(x): x not in list ValueError: list.remove(x): x 不在列表中

Even when I try to assign the index of the word to an int the same error is shown.即使我尝试将单词的索引分配给 int 也会显示相同的错误。

You should not modify a list while you are iterating through it.在遍历列表时不应修改列表。 Your indices are changing when you remove something.当您删除某些内容时,您的索引会发生变化。 Tr to simplify the task. Tr 来简化任务。

I would store word counts in a dictionary:我会将字数存储在字典中:

goodwords = ["a", "my", "the", "I", "long", "up", "on"]
count = [26, 16, 16, 15, 12, 11, 11 ]
wordcounts = dict(zip(goodwords, count))

To have only longer words, filter them:要只有更长的单词,请过滤它们:

wordcounts = {word: c for word, c in wordcounts.items()
              if len(word) > 3}

BTW, you can get the first part of the job done using the built-in collections.Counter :顺便说一句,您可以使用内置collections.Counter完成工作的第一部分:

>>> wordcounts = collections.Counter("one word and one more word".split())
>>> wordcounts
Counter({'one': 2, 'word': 2, 'and': 1, 'more': 1})

You can affect the loop if you modify a list you're looping in. Try creating a new list with the correct values instead.如果修改要循环的列表,则可能会影响循环。请尝试使用正确的值创建新列表。

for word in allwords:
if len(word)>3:
        goodwords.append(word)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM