python - 循环遍历字符串列表并使用正则表达式条件编辑它们(python)
问题描述
所以,我有一个这样的清单:
lst = ['A1.', 'A1.0.', '1.', '2.', 'A2.', '1.1.', 'A3.', 'A3.0.', '1.1.1.']
并且想遍历每个字符串,如果这个字符串不以 a 开头,(^A\d+\.)
则从前一个字符串项中获取此模式并将其添加到当前字符串的开头。因此,最终列表应如下所示:
target = ['A1.', 'A1.0.', 'A1.1.', 'A1.2.', 'A2.', 'A2.1.1.', 'A3.', 'A3.0', 'A3.1.1.1.']
在没有太多“for”循环的情况下实现这一目标的最有效方法是什么?我对 Python 很陌生。
解决方案
像这样的东西?
import re
lst = ['A1.', 'A1.0.', '1.', '2.', 'A2.', '1.1.', 'A3.', 'A3.0.', '1.1.1.']
new_lst=[]
last_correct_item = ""
pattern = re.compile("(^A\d+\.)")
for item in lst:
match = pattern.match(item)
if match:
last_correct_item = item[match.start():match.end()]
new_lst.append(item)
else:
new_item = last_correct_item + item
new_lst.append(new_item)
print(new_lst)
# ['A1.', 'A1.0.', 'A1.1.', 'A1.2.', 'A2.', 'A2.1.1.', 'A3.', 'A3.0.', 'A3.1.1.1.']
推荐阅读
- ios - 水平stackView中imageView和标签之间的水平间距
- angular - 如何向/从 ngx-bootstrap 模式传递和接收数据?
- proxy - MITMPROXY 使输出对文件具有可读性
- php - 使用 php 在主页上显示名称(来自 mySQL 的数据)
- angularjs - 如何在 angularJS 移动网站中录制视频和音频
- go - 为什么将遍历从按顺序更改为前/后顺序会使“练习:等效二叉树”中的答案错误?
- dust.js - 同时访问嵌套数组中的外部和内部索引
- c# - 比较两个数据表的值,如果不同,则添加到新数据表以进行添加、更新和删除
- java - 新场景启动后代码如何执行
- angular - 如何从目录访问打字稿中的文件名