如何统计Python列表内各字符串的字母重复出现次数
现有代码问题梳理
- 变量引用错误:定义的列表变量为
my_lst,代码中使用未定义的lst,运行直接报错 - 循环参数错误:
range()仅接受整数参数,直接传入列表会触发类型错误 - 语法缺失:所有
if/elif行末尾缺少冒号:,不符合Python语法规范 - 计数逻辑错误:仅用一个全局变量统计所有字母,无法区分不同字母的计数;且仅判断了A/V/B/X四个字母,无法适配全字符统计需求
- 输出格式不匹配:没有按要求逐行输出每个字母和对应的计数
优化实现代码
方案1:原生字典实现(无需引入额外库)
my_lst =['AVBXXX' , 'GAHJJKSL' ] for s in my_lst: # 输出带markdown格式的行,不需要格式可去掉反引号 print(f"List : `{s}`") count_dict = {} for char in s: count_dict[char] = count_dict.get(char, 0) + 1 for char, num in count_dict.items(): print(f"{char} - {num}") # 不同字符串结果之间加空行分隔 print()
方案2:使用标准库Counter实现(代码更简洁)
from collections import Counter my_lst =['AVBXXX' , 'GAHJJKSL' ] for s in my_lst: print(f"List : `{s}`") count_dict = Counter(s) for char, num in count_dict.items(): print(f"{char} - {num}") print()
运行上述代码即可得到你要求的输出格式。
内容的提问来源于stack exchange,提问作者user16871229
相关产品推荐
相关产品推荐

