如何按顺序统计序列中连续同类字母的出现数量?
连续同类字母分段统计实现
你原来的代码仅做全局指定字符的匹配计数,没有记录连续段的状态,无法区分不同位置的同字符分段,以下是可直接实现需求的代码:
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
相关产品推荐
相关产品推荐

