使用Python字典统计字符串中各字符出现次数并解决输出重复问题
问题根源
原有代码直接遍历输入字符串的每一个字符,只要字符出现就打印统计结果,同一个字符出现多少次就会重复打印多少次。
修复代码
你可以新增一个集合记录已经输出过的字符,遍历到已经记录过的字符直接跳过即可,同时用end=' '让所有结果打印在同一行,匹配你需要的输出格式:
s= input("input string: ") seen = set() for n in s: if n not in seen: print({n:s.count(n)}, end=' ') seen.add(n)
输入chocolate coco后输出效果如下:
{'c': 4} {'h': 1} {'o': 4} {'l': 1} {'a': 1} {'t': 1} {'e': 1} {' ': 1}
如果需要处理长字符串,推荐用collections.Counter优化统计效率,避免每次调用count都遍历整个字符串:
from collections import Counter s= input("input string: ") char_count = Counter(s) seen = set() for n in s: if n not in seen: print({n: char_count[n]}, end=' ') seen.add(n)
内容的提问来源于stack exchange,提问作者wendy forehead
相关产品推荐
相关产品推荐

