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

如何修正Python字符串字母频率统计代码:去重并按字母序排序输出

修正方案

问题分析

原代码存在两个核心问题:

  • 重复输出同一字符:循环遍历字符串的每个字符,每遇到一次符合条件的字符就打印一次,导致同一字符多次输出。
  • 未按字典序排列:输出顺序是字符在原字符串中出现的顺序,而非字典序。

解决思路

  1. 高效统计字符频率:避免每次调用count()方法(时间复杂度O(n²)),改用字典或collections.Counter一次性统计所有字符的出现次数(时间复杂度O(n))。
  2. 过滤并排序:筛选出出现次数大于1的字符,再按字典序排序。
  3. 批量输出:遍历排序后的字符列表,依次打印字符及其次数。

修正代码(两种实现方式)

方式一:使用collections.Counter(简洁高效)

from collections import Counter

s = input().strip()
char_counts = Counter(s)

# 筛选出现次数>1的字符并按字典序排序
sorted_chars = sorted([char for char in char_counts if char_counts[char] > 1])

for char in sorted_chars:
    print(char, char_counts[char])

方式二:手动统计(无需导入模块)

s = input().strip()
count_dict = {}

# 手动统计每个字符的出现次数
for char in s:
    count_dict[char] = count_dict.get(char, 0) + 1

# 筛选并排序
sorted_chars = sorted([k for k in count_dict if count_dict[k] > 1])

for char in sorted_chars:
    print(char, count_dict[char])

测试验证

输入示例:

thequickbrownfoxjumpsoverthelazydog

输出结果:

e 3
h 2
o 4
r 2
t 2
u 2

完全符合期望输出。

内容的提问来源于stack exchange,提问作者Codeer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:24:10