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

Python实现Markdown标题转层级编号列表时的子节计数错误修正问询

问题诊断

嘿,我找到问题根源啦!你的子标题计数器sh_no在遇到新的一级标题时没有重置——当处理完# t2(此时h_no变为2)后,再遇到# t4(h_no变为3),sh_no还停留在之前的3,导致后续子标题直接从4开始计数,才出现了3.4. s1这种错误编号。

修正方案

我们只需要在每次处理一级标题(以# 开头的行)时,把sh_no重置为0,这样后续属于当前一级标题的子标题就能从1重新开始累加。同时我还优化了循环写法,让代码更符合Python风格:

modified_lst = []
h_no = 0
sh_no = 0
for item in a_lst:
    # 处理一级标题
    if item.startswith('# '):
        h_no += 1
        sh_no = 0  # **关键修改**:遇到新一级标题时重置子标题计数器
        modified_lst.append(item.replace('#', f"{h_no}.", 1))
    # 处理二级标题
    elif item.startswith('## '):
        sh_no += 1
        modified_lst.append(item.replace('##', f"{h_no}.{sh_no}.", 1))

效果验证

运行修正后的代码,得到的结果完全符合你的预期:
modified_lst = ['1. title', '1.1. subtitle', '1.2. s2 ', '1.3. S3', '2. t2', '3. t4', '3.1. s1', '3.2. s2']

另外,你原代码里的temp_hno变量其实是多余的,现在的逻辑不需要额外判断,直接通过重置sh_no就能保证每个一级标题下的子标题从1开始编号~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 15:27:35