Home > Enterprise >  Change list elements with updated numerical order
Change list elements with updated numerical order

Time:05-25

I have a list as follows:

L1 = ['asd', 'pqr', 'Mn2', 'Mn3', 'xyz']
L2 = ['asd', 'pqr', 'Mn7', 'Mn8', 'Mn9', 'xyz']

I am trying to get the following:

L1 = ['asd', 'pqr', 'Mn1', 'Mn2', 'xyz']
L2 = ['asd', 'pqr', 'Mn1', 'Mn2', 'Mn3', 'xyz']

i.e. everytime the Mn1, Mn2, ... series occurs in the list, I need to change them to update their chronology. In the L2, Mn7, Mn8, Mn9 were updated to Mn1, Mn2, Mn3.

The Mn series cam be of an arbitrary number i.e. Mn11, Mn12, Mn13, Mn14 etc also but whenever they happen they are in numerical order

I am not sure how to approach this.

CodePudding user response:

You can use regular expression to substitute the numbers. For example:

import re
from itertools import count


L1 = ["asd", "pqr", "Mn2", "Mn3", "xyz"]
L2 = ["asd", "pqr", "Mn7", "Mn8", "Mn9", "xyz"]


def change(lst):
    c, pat = count(1), re.compile(r"Mn(\d )")
    return [pat.sub(lambda x: f"Mn{next(c)}", v) for v in lst]


L1 = change(L1)
L2 = change(L2)

print(L1)
print(L2)

Prints:

['asd', 'pqr', 'Mn1', 'Mn2', 'xyz']
['asd', 'pqr', 'Mn1', 'Mn2', 'Mn3', 'xyz']
  • Related