You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 06:45:03