如何统计字符串首字母出现频率并找出最高频首字母?
找出字符串列表中频率最高的首字母
基础实现(无需额外库)
先通过一次遍历统计每个首字母的出现次数,再遍历统计结果找出频率最高的字母:
words = ['home', 'dog', 'park', 'house', 'hotel', 'fire'] char_counts = {} # 统计首字母出现次数 for word in words: # 统一转小写,避免大小写差异影响统计 first_char = word[0].lower() char_counts[first_char] = char_counts.get(first_char, 0) + 1 # 找出频率最高的首字母 max_count = max(char_counts.values()) most_common_chars = [char.upper() for char, cnt in char_counts.items() if cnt == max_count] # 输出结果 if len(most_common_chars) == 1: print(f"出现频率最高的首字母是 {most_common_chars[0]},共出现 {max_count} 次") else: print(f"出现频率最高的首字母有 {', '.join(most_common_chars)},均出现 {max_count} 次")
简洁实现(使用collections.Counter)
Python标准库的Counter类可以直接帮我们完成统计工作,代码更简洁:
from collections import Counter words = ['home', 'dog', 'park', 'house', 'hotel', 'fire'] # 提取所有首字母并统一大小写 first_chars = [word[0].lower() for word in words] # 统计频率 counts = Counter(first_chars) # 获取频率最高的项,处理多字母并列的情况 max_count = counts.most_common(1)[0][1] most_common_chars = [char.upper() for char, cnt in counts.items() if cnt == max_count] # 输出结果 if len(most_common_chars) == 1: print(f"出现频率最高的首字母是 {most_common_chars[0]},共出现 {max_count} 次") else: print(f"出现频率最高的首字母有 {', '.join(most_common_chars)},均出现 {max_count} 次")
关于双层循环的问题
你之前用双层循环没得到预期结果,大概率是计数逻辑出错了——比如重复遍历统计、没有正确累加次数。上面的方法只需要两次线性遍历(一次统计、一次找最大值),逻辑更清晰,也更容易排查问题。
内容的提问来源于stack exchange,提问作者Francesco
相关产品推荐
相关产品推荐

