首页 > 解决方案 > for循环没有遍历列表中的所有元素

问题描述

我又来了。我正在做一个小的 Python 练习,看看我能做多好。(顺便说一句,我是初学者)。所以我收到了一个问题,要求我说出一个单词在给定字符串中出现的次数。看起来很容易。我写下了代码。这里是:

# Question 12:
    # Write a Python program to count the occurrences of each word in a given sentence.

def word_occurrences(string):
    words = string.split(sep=' ')
    words_len = {}
    for each_word in words:
        counter = 1
        words_len[each_word] = counter
        words.remove(each_word)
        if each_word in words:
            while each_word in words:
                counter += 1
                words_len[each_word] = counter
                words.remove(each_word)
        continue
    return words_len

print(word_occurrences('Abdullah is Abdullah at work'))

我的方法是使用句子中的单词制作一个列表,然后对每个单词进行计数,删除该单词,如果该单词仍然在该列表中找到,则表示该单词再次出现。因此,如果该单词仍在其中,我会继续删除该单词,并为每次删除进行计数,直到该单词不再出现,然后继续下一个单词。但是这段代码,尤其是 for 循环,似乎在元素之间跳转。它给了我这个输出:

{'Abdullah': 2, 'at': 1}

当期望或预期的输出是:

{'Abdullah': 2, 'is': 1, 'at': 1, 'work': 1}

我不知道为什么会这样。任何帮助/解释都将被深深地理解。

标签: pythonlistloopsfor-loop

解决方案


不要破坏你的工作,而是使用预定义的库会有很长的路要走。

from collections import Counter
def word_occurrences(string):
    words = string.split(" ")
    return Counter(words)

string.split(" ")将字符串拆分为“单词”列表。该Counter函数仅返回这些单词计数的字典。


推荐阅读