Python 我的一个循环不工作,有人能给我一个原因吗?
我试图用python创建一个单词计数器,它打印最长的单词,然后按频率对超过5个字母的所有单词进行排序。最长的单词是有效的,计数器也是有效的,我只是不知道如何让它只检查5个字母。如果我运行它,它会工作,但5个字母以下的单词仍然存在 以下是我的代码:Python 我的一个循环不工作,有人能给我一个原因吗?,python,word-count,Python,Word Count,我试图用python创建一个单词计数器,它打印最长的单词,然后按频率对超过5个字母的所有单词进行排序。最长的单词是有效的,计数器也是有效的,我只是不知道如何让它只检查5个字母。如果我运行它,它会工作,但5个字母以下的单词仍然存在 以下是我的代码: print(max(declarationWords,key=len)) for word in declarationWords: if len(word) >= 5: declarationWords.remove(
print(max(declarationWords,key=len))
for word in declarationWords:
if len(word) >= 5:
declarationWords.remove(word)
print(Counter(declarationWords).most_common())
您可以创建新的列表,其中包含符合您的条件(筛选器)的单词,并使用它:
>>> s = ["abcdf", "asdfasdf", "asdfasdfasdf", "abc"]
>>> new_s = [x for x in s if len(x) >= 5]
>>> new_s
['abcdf', 'asdfasdf', 'asdfasdfasdf']
>>>
或者一点其他的方法
>>> new_s = filter(lambda x: len(x) >= 5, s)
>>> Counter(new_s)
Counter({'abcdf': 1, 'asdfasdf': 1, 'asdfasdfasdf': 1})
我看到您可以发现这些更改对您的代码很有帮助:D
Longest_words=[]
print(max(declarationWords,key=len))
for word in declarationWords:
if len(word) >= 5:
Longest_words.append(word)
print(Counter(Longest_words).most_common())
不要编辑正在迭代的iterable。它破坏了索引。我建议阅读。