Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

looping through a list of strings and edit them with a regex condition (python)

So, I have a list like that:

lst = ['A1.', 'A1.0.', '1.', '2.', 'A2.', '1.1.', 'A3.', 'A3.0.', '1.1.1.']

And would like to iterate through each string, and if this string does not start with a (^Ad+.), take this pattern from the previous string item and add it to the beginning of the current one. So, the final list should look like that:

target = ['A1.', 'A1.0.', 'A1.1.', 'A1.2.', 'A2.', 'A2.1.1.', 'A3.', 'A3.0', 'A3.1.1.1.']

What is the most efficient way to achieve this without too many 'for' loops? I am quite new in Python.

question from:https://stackoverflow.com/questions/66049040/looping-through-a-list-of-strings-and-edit-them-with-a-regex-condition-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try:

import re 
pat2 = re.compile('(Ad+)|(^d.*.$)')

for l in range(1,len(lst)):
    a1, val1 = re.findall(pat2, lst[l-1])[0]
    a2, val2 = re.findall(pat2, lst[l])[0]
    if not a2:
        lst[l] = f"{a1}.{lst[l]}"

lst:

['A1.',
 'A1.0.',
 'A1.1.',
 'A1.2.',
 'A2.',
 'A2.1.1.',
 'A3.',
 'A3.0.',
 'A3.1.1.1.']

explanation:

  • I am changing the original list.
  • I will take the previous list element find the prefix and if my current doesn't have one I will append the previous one prefix.

pat2 will capture

'1.0.0.' ==> [('', '1.0.0.')]

'A1.0.0.' ==> [('A1', '')]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...