如何用for/while循环和if语句找出列表中最常见的单词?
用基础语法找出列表中最常见单词的实现方案
嘿,刚学编程的话,咱们就用你熟悉的for/while循环和if语句来搞定这个需求~先看看你写的函数里的小问题:函数里的hello和first都没定义哦,而且逻辑上有点绕,咱们重新梳理一遍怎么实现。
第一步:先学会统计单个单词的出现次数
首先,咱们先写个小逻辑,统计某个单词在列表里出现了多少次——完全用基础语法:
def count_word(lst, target_word): count = 0 # 遍历列表里的每个元素 for word in lst: if word == target_word: count += 1 return count
这个函数的作用很简单:传入列表和要统计的单词,返回这个单词出现的次数。比如调用count_word(list1, "me"),就会返回4,正好是list1里"me"的出现次数。
第二步:找出列表里出现次数最多的单词
接下来,咱们要遍历列表里的每个单词,统计它们的出现次数,然后记录次数最多的那个(那些)单词。
版本1:返回第一个遇到的最常见单词
如果只需要返回任意一个出现次数最多的单词,这个版本足够用:
def find_most_common(lst): max_count = 0 most_common = "" # 遍历列表里的每一个单词 for current_word in lst: # 统计当前单词的出现次数 current_count = 0 for word in lst: if word == current_word: current_count += 1 # 如果当前单词的次数比之前的最大次数多,就更新记录 if current_count > max_count: max_count = current_count most_common = current_word return most_common, max_count
咱们来测试一下你的两个列表:
list1 = ["cry", "me", "me", "no", "me", "no", "no", "cry", "me"] list2 = ["cry", "cry", "cry", "no", "no", "no", "me", "me", "me"] # 测试list1 word1, count1 = find_most_common(list1) print(f"list1里最常见的单词是'{word1}',一共出现了{count1}次") # 输出:list1里最常见的单词是'me',一共出现了4次 # 测试list2 word2, count2 = find_most_common(list2) print(f"list2里最常见的单词是'{word2}',一共出现了{count2}次") # 输出:list2里最常见的单词是'cry',一共出现了3次(因为三个单词次数相同,返回第一个遇到的)
版本2:返回所有出现次数最多的单词
如果列表里有多个单词出现次数一样多(比如list2里的"cry"、"no"、"me"都是3次),想要把它们都找出来,可以稍微修改一下逻辑:
def find_all_most_common(lst): max_count = 0 most_common_words = [] # 第一步:先找出最大的出现次数 for current_word in lst: current_count = 0 for word in lst: if word == current_word: current_count += 1 if current_count > max_count: max_count = current_count # 第二步:找出所有出现次数等于最大次数的单词,还要手动去重(不能用集合的话,就判断是否已经在列表里) for current_word in lst: current_count = 0 for word in lst: if word == current_word: current_count += 1 if current_count == max_count and current_word not in most_common_words: most_common_words.append(current_word) return most_common_words, max_count
测试list2的话,就会返回["cry", "no", "me"],次数是3次,完美覆盖所有情况。
小说明
这个方法虽然效率不算最高(因为会重复统计同一个单词的次数),但完全符合你要求的“只用基础语法”的限制,而且逻辑非常直观,适合刚学编程的你理解核心思路~
内容的提问来源于stack exchange,提问作者user12042014




