首页 > 解决方案 > 创建分层编号的部分标题会错误地计算子部分

问题描述

a_lst = [
    '# title',
    '## subtitle',
    '## s2  ',
    '## S3',
    '# t2',
    '# t4',
    '## s1',
    '## s2'
]

我想将上面的列表转换成这个列表:

req_lst = [
    '1. title',
    '1.1. subtitle',
    '1.2. s2  ',
    '1.3. S3',
    '2. t2',
    '3. t4',
    '3.1 s1',
    '3.2. s2'
]

为此,我编写了以下代码:

modified_lst = []
h_no = 0
sh_no = 0

for i in range(len(a_lst)):
    # If string starts with '# ' it is a heading
    if a_lst[i][:2] == '# ':
        h_no += 1
        temp_hno = h_no
        modified_lst.append(a_lst[i].replace('#', str(h_no)+'.', 1))
    # If the string starts with '## ' it is a subheading
    elif a_lst[i][:3] == '## ':
        if temp_hno  == h_no:
            sh_no += 1
            modified_lst.append(a_lst[i].replace('##', str(h_no)+ '.'+ str(sh_no) + '.', 1))
        else:
            sh_no = 1
            modified_lst.append(a_lst[i].replace('##', str(h_no)+ '.'+ str(sh_no) + '.', 1))

但这给了我这个modified_lst

modified_lst = [
    '1. title',
    '1.1. subtitle',
    '1.2. s2  ',
    '1.3. S3',
    '2. t2',
    '3. t4',
    '3.4. s1',
    '3.5. s2'
]

如何为小节s1s2以下创建正确的编号t4

标签: pythonlisttableofcontents

解决方案


sh_no每次看到新的 # 时都应该重置。所以将第一个修改为if

if a_lst[i][:2] == '# ':
    sh_no = 0
    h_no += 1
    temp_hno = h_no
    modified_lst.append(a_lst[i].replace('#', str(h_no)+'.', 1))

推荐阅读