简体   繁体   English

for循环没有遍历列表中的所有元素

[英]for loop not iterating over all the element in a list

me again here.我又来了。 I am taking a small Python exercise to see how well can I do.我正在做一个小的 Python 练习,看看我能做多少。 (I am a beginner btw). (顺便说一句,我是初学者)。 So I got a question that asked me to tell how many times a word was present in a given string.所以我收到了一个问题,要求我说出一个单词在给定字符串中出现的次数。 Seemed pretty easy.看起来很容易。 I wrote down the code.我写下了代码。 Here it is:这里是:

# 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'))

My approach was to make a list using words of the sentence and then for each word, count up, remove that word, and if that word is still found in that list, it means that the word is appearing again.我的方法是使用句子中的单词制作一个列表,然后对每个单词进行计数,删除该单词,如果该单词仍然在该列表中找到,则表示该单词再次出现。 So I keep removing the word if it's still in there and counting up for each removal until there are no other occurrences of that word and I move on to the next word.因此,如果该单词仍在其中,我会继续删除该单词,并为每次删除进行计数,直到该单词不再出现,然后继续下一个单词。 But this code, particularly the for loop, seems to jump between elements.但是这段代码,尤其是 for 循环,似乎在元素之间跳转。 It gives me this output:它给了我这个 output:

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

When the desired or expected output was:当所需或预期的 output 为:

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

I have no idea why is this happening.我不知道为什么会这样。 Any help/explanation will be deeply appericiated.任何帮助/解释都将被深深地理解。

Not to undermine your work but using predefined libraries will go a long way.不要破坏您的工作,而是使用预定义的库将使 go 有很长的路要走。

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

string.split(" ") splits the string into a list of "words". string.split(" ")将字符串拆分为“单词”列表。 The Counter function simply returns a dictionary of the counts of these words. Counter function 只返回这些单词计数的字典。

You are removing items from the list while iterating over it您在迭代列表时从列表中删除项目

def word_occurrences(string):
    words = string.split(" ")
    word_freq = {}
    for word in words:
        if(word in word_freq):
            word_freq[word] += 1
        else:
            word_freq[word] = 1
    return word_freq
print(word_occurrences('Abdullah is Abdullah at work'))

The above code outputs上面的代码输出

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM