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

字符连续计数程序优化:仅移除计数为1的数字而非所有'1'

问题描述

我正在开发一个字符连续出现次数计数程序,逻辑是统计字符连续出现的次数,遇到不同字符时将计数器重置为1,每个字符后标注对应的计数值。目前程序能正常完成计数,但希望当计数值为1时不显示该数字(例如输入hello应输出hel2o)。但现有代码会移除字符串中所有的'1',导致如字符h连续出现14次时,错误输出h4而非预期的h14。

现有代码如下:

text = "aaabbbabcccc"+ " " #I added space in case it does not get the last character of the string!
counter = 0
n = ""
decom = ""
for x in range(0,len(text)):
    if text[x] == text[x-1]:
        counter+=1; 
    else:
         counter=1     
    decom+=f"{text[x]}{str(counter)}"if x+1!=len(text) and text[x]!=text[x+1] else ""
    if counter==1:
      n = decom.replace(str(counter),"")
print("With 1 not removed:")
print(decom.strip()) #This one calculates more accurate than the one with 1 removed
print("With 1 removed:")
print(n.strip()) #This one removes all the ones in the code..

请问如何实现仅移除计数值为1的数字,而非字符串中所有的'1'?

解决方案

核心问题在于你用了replace("1", "")的方式,这会把所有'1'字符都删掉,不管它是计数值还是连续次数的一部分。正确的做法是在构建结果字符串的时候就判断是否要添加计数值,而不是事后替换。

修正后的代码逻辑:

  1. 遍历字符串时,跟踪当前字符和连续计数
  2. 当遇到不同字符(或到达字符串末尾)时,根据计数决定是否添加数字:
    • 如果计数>1,就拼接字符+计数
    • 如果计数=1,只拼接字符

修正后的代码:

text = "aaabbbabcccc"  # 不需要额外加空格,调整逻辑即可处理末尾字符
result = []
if not text:
    print("")
    exit()

current_char = text[0]
counter = 1

for char in text[1:]:
    if char == current_char:
        counter += 1
    else:
        # 遇到不同字符,先把之前的字符和计数加入结果
        result.append(current_char + (str(counter) if counter > 1 else ""))
        current_char = char
        counter = 1
# 处理最后一组字符
result.append(current_char + (str(counter) if counter > 1 else ""))

final_output = "".join(result)
print("处理后结果:")
print(final_output)

代码说明

  • 用列表result拼接结果,比直接字符串拼接更高效(字符串是不可变对象,频繁拼接会产生大量临时对象)
  • 遍历到不同字符时,立即处理前一组的字符和计数,根据counter是否大于1决定是否添加数字
  • 循环结束后单独处理最后一组字符,避免遗漏
  • 无需额外添加空格,逻辑已覆盖末尾字符的处理

测试示例:

  • 输入hello,输出hel2o
  • 输入hhhhhhhhhhhhhh(14个h),输出h14
  • 输入aaabbbabcccc,输出a3b3ab4

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 10:33:29