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

Python如何按出现顺序统计字符串字符频率并按指定格式输出

Python实现指定格式的字符频率统计

你之前找的全局频率统计方案不符合需求,原因是该方案统计的是整个字符串中所有相同字符的总出现次数,且默认不保留字符的出现顺序。根据你给出的示例,实际需求是统计连续出现的相同字符的数量,同时保留原字符串的空格分隔逻辑,多个连续空格合并为单个分隔符。

实现代码

def count_continuous_chars(s: str) -> str:
    # 先按空格拆分字符串,自动合并多个连续空格
    words = s.split()
    res = []
    for word in words:
        if not word:
            continue
        word_res = []
        current_char = word[0]
        count = 1
        # 遍历单词内的字符,统计连续相同字符
        for c in word[1:]:
            if c == current_char:
                count += 1
            else:
                word_res.append(f"{current_char}{count}")
                current_char = c
                count = 1
        # 加上最后一组字符的统计结果
        word_res.append(f"{current_char}{count}")
        res.append(''.join(word_res))
    # 用单个空格拼接所有单词的处理结果
    return ' '.join(res)

测试验证

运行以下测试用例可匹配你给出的预期输出:

  • count_continuous_chars("aaaa") 返回 a4
  • count_continuous_chars("abb") 返回 a1b2
  • count_continuous_chars("abbb cc a") 返回 a1b3 c2 a1
  • count_continuous_chars("bbbaaacddddee") 返回 b3a3c1d4e2
  • count_continuous_chars("a b") 返回 a1 b1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:15:07