python - 创建分层编号的部分标题会错误地计算子部分
问题描述
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'
]
如何为小节s1
及s2
以下创建正确的编号t4
?
解决方案
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))
推荐阅读
- amazon-web-services - AWS Lambda 访问数据每小时刷新一次
- java - 我无法显示我在 jpanel 中加载的第二张图片
- java - 在 Spring Data 存储库的单元测试中忽略唯一约束
- c# - 无法在 Kubernetes 中从工作连接到服务
- kotlin - 如何以编程方式更改材质卡视图主题样式?
- javascript - 如何在 nodeJs 中使用 stream-json 中的管道写入文件?
- tensorflow - TensorFlow 对象检测:继续训练
- python - 我将数据从 csv 加载到 Python Pandas 并尝试将列设置为行(日期重复)
- java - 如何使用代码从 apk 中提取 SHA/MDA?
- python - 如何将标签添加到子图行和列?