Python字符串字母占比计算问题:pro_dict返回空字典如何解决?
解决字符串字母占比计算问题
你的代码返回空字典的核心问题有两个:
pro_dict初始为空,后续遍历它的items()循环根本不会执行,自然无法填充数据- 计算占比时错误地用字符本身除以字符串长度,应该用字符的出现次数除以总长度
方法一:基于原代码修改
def letter_proportion(seq): char_count = {} # 统计每个字符的出现次数 for character in seq: if character in char_count: char_count[character] += 1 else: char_count[character] = 1 # 计算并填充占比字典 pro_dict = {} total_length = len(seq) for character, count in char_count.items(): pro_dict[character] = round(count / total_length, 3) # 保留三位小数 return pro_dict
方法二:用内置工具简化代码
Python内置的collections.Counter可以直接帮你统计字符出现次数,代码更简洁:
from collections import Counter def letter_proportion(seq): char_count = Counter(seq) total_length = len(seq) return {char: round(count / total_length, 3) for char, count in char_count.items()}
测试示例
调用letter_proportion("AAABCCCC")会返回{'A': 0.375, 'B': 0.125, 'C': 0.5},完全符合你需要的格式。
内容的提问来源于stack exchange,提问作者Zach
相关产品推荐
相关产品推荐

