首页 > 解决方案 > 循环遍历字符串列表并使用正则表达式条件编辑它们(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 很陌生。

标签: pythonregexlist

解决方案


像这样的东西?

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.']

推荐阅读