Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python &引用;ValueError:list。删除(x):x不在列表中;当x在列表中时_Python - Fatal编程技术网

Python &引用;ValueError:list。删除(x):x不在列表中;当x在列表中时

Python &引用;ValueError:list。删除(x):x不在列表中;当x在列表中时,python,Python,我尝试过许多可能的解决办法,但没有一个奏效。我的代码是一个简单的单词计数器,它计算歌词中单词的频率。因为短单词不应该被计算在内,所以我写了这段代码。我的单词和它们的计数表是这样的 goodwords=["a", "my", "the", "I", "long", "up", "on"] count=[26, 16, 16, 15, 12, 11, 11

我尝试过许多可能的解决办法,但没有一个奏效。我的代码是一个简单的单词计数器,它计算歌词中单词的频率。因为短单词不应该被计算在内,所以我写了这段代码。我的单词和它们的计数表是这样的

 goodwords=["a", "my", "the", "I", "long", "up", "on"] 
 count=[26, 16, 16, 15, 12, 11, 11 ]
所以我写了这个代码来过滤掉短单词

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

        
对于goodwords中的单词:

如果len(word)在遍历列表时不应修改列表。当您删除某些内容时,索引正在更改。简化任务

我会将字数存储在字典中:

goodwords = ["a", "my", "the", "I", "long", "up", "on"]
count = [26, 16, 16, 15, 12, 11, 11 ]
wordcounts = dict(zip(goodwords, count))
要仅包含较长的单词,请过滤它们:

wordcounts = {word: c for word, c in wordcounts.items()
              if len(word) > 3}
顺便说一句,您可以使用内置的:


如果修改正在循环的列表,则可能会影响循环。 请尝试使用正确的值创建一个新列表

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

为什么你没有为此使用词典呢?你试着用
remove
一次删除一个单词,一次删除一个索引-这两者都不行。@Thierrylahuille他们正在从两个不同的列表中删除。
goodwords.index
保证返回一个小于
goodwords
长度的数字,即7;因此,仅包含大于10的数字的列表
count
不能包含您试图删除的值。为什么你认为你的代码是正确的?@bereal我的意思可能不清楚:OP尝试通过将单词传递给
remove
来删除一个单词,还有一次尝试通过将其索引传递给
remove
来删除一个计数,但同样的方法在一种情况下不能以一种方式工作,在另一种情况下不能以另一种方式工作。他打算在第二种情况下使用
del
。这将是一个很好的解决方案,谢谢。但是python为代码的第二部分(过滤)提供了一个“无效语法”错误。我的理解力不太好。你能解释一下吗?@tavasencasis我在
wordcounts=dict(zip(goodwords,count)
中有一个错误。我忘了关闭最后一个括号。这可能在它后面的行中显示为一个错误。现在再试一次。
for word in allwords:
if len(word)>3:
        goodwords.append(word)