You need to enable JavaScript to run this app. 如何按顺序统计序列中连续同类字母的出现数量?
优惠活动
大模型
产品
解决方案
定价
更多

如何按顺序统计序列中连续同类字母的出现数量?

连续同类字母分段统计实现

你原来的代码仅做全局指定字符的匹配计数,没有记录连续段的状态,无法区分不同位置的同字符分段,以下是可直接实现需求的代码:

def count_continuous_chars(input_str):
    # 预处理:提取所有字母,过滤逗号、空格等非字母字符
    chars = [c for c in input_str if c.isalpha()]
    if not chars:
        return ""
    
    result = []
    current_char = chars[0]
    current_count = 1

    for c in chars[1:]:
        if c == current_char:
            current_count += 1
        else:
            # 拼接单段统计结果,数量大于1时后缀加s
            result.append(f"{current_count} {current_char}{'s' if current_count > 1 else ''}")
            current_char = c
            current_count = 1
    # 补充最后一段统计结果
    result.append(f"{current_count} {current_char}{'s' if current_count > 1 else ''}")
    return ", ".join(result)

测试示例

test_input = "L, L, L, L, R,L ,R ,L ,A ,A"
print(count_continuous_chars(test_input))

输出结果:

4 Ls, 1 R, 1 L, 1 R, 1 L, 2 As

后续需求适配说明

后续需要处理带句点关联的字符剔除需求时,只需修改预处理逻辑,在提取字符步骤过滤掉需要剔除的字符即可,核心统计逻辑无需调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 21:42:00