0

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!

1
  • 1
    Could you show us what you have tried? Commented Nov 25, 2020 at 15:56

3 Answers 3

2

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Very nice with Walrus operator as well. We can remove also ,1 in replace command, right?
@physiker--1 is there to keep strings such as "172.16.254.1" (an IP address) from being considered a number.
0

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)

Comments

0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.