physiker
physiker

Reputation: 919

python renaming list element based on another list

I have two lists as following

A=['a','b','c']

B=['0_txt1','0_txt2','1_txt1','1_txt2','2_txt1','2_txt2']

I should rename prefix number in B elements with corresponding list element from A, so the desired output is:

B=['a_txt1','a_txt2','b_txt1','b_txt2','c_txt1','c_txt2']

How can I do this by reading and replacing elements? Thank you!

Upvotes: 0

Views: 849

Answers (3)

harada
harada

Reputation: 182

Here is a simple loop that will go through and see if the indices of A match the leading numbers of items in B, then replace the numbers accordingly

C = []

for string in B:
    for x in A:
        if string.startswith(str(A.index(x))):
            C.append(string.replace(str(A.index(x)), x, 1))

Upvotes: 0

DarrylG
DarrylG

Reputation: 17156

Using list comprehension:

B = [x.replace(x.split("_")[0],  A[int(x.split("_")[0])], 1) for x in B]

Or using Walrus Operator (Python 3.8+) to avoid double calculating x.split("_")[0]

B = [x.replace((p:=x.split("_")[0]),  A[int(p)], 1) for x in B]

Upvotes: 2

wasif
wasif

Reputation: 15478

Try list comprehensions with format strings, enumerate and zip

A=['a','b','c']

B=['0_txt1','0_txt2','1_txt1','1_txt2','2_txt1','2_txt2']

C = [f"{z}_{x.split('_')[1]}" for x in B for y,z in enumerate(A) if x.split('_')[0] == str(y)]

print(C)

Upvotes: 0

Related Questions