【问题标题】:One of my loops not working, can somebody give me a reason why?我的一个循环不起作用,有人可以给我一个原因吗?
【发布时间】:2021-01-16 16:12:37
【问题描述】:

我正在尝试在 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())

【问题讨论】:

标签: python word-count


【解决方案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())

【讨论】:

    【解决方案2】:

    您可以创建新列表,其中包含符合您的条件(过滤器)的单词并使用它:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多