我的循环之一不起作用,有人可以给我一个原因吗?

问题描述

我正在尝试在python中创建一个单词计数器,该计数器打印最长的单词,然后按频率对5个字母以上的所有单词进行排序。最长的单词有效,而计数器有效,我只是想不出如何使它仅检查5个以上的字母。如果我运行它,它可以工作,但是5个字母以下的单词仍然存在。

这是我拥有的代码

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())

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...