0

I have two list variables:

a = ["a", "b"]
b = ["a (x)"]

I need to find and replace all elements in list a with elements from list b where substring of element before ( from list b is equal to element from list a. So I need to get this:

a = ["a (x)", "b"]
b = ["a (x)"]

It is a bit complicated to exlplain, but I hope you understand.

This is what I have so far, but I don't know how to continue.

for bx in b:
    for ax in a:
        if ax == bx[:bx.find(" (")]:
            #I don't know what to do next

Do you have some ideas, please?

1 Answer 1

4

This is one way. First create a dictionary mapping, then apply it in a list comprehension.

a = ["a", "b"]
b = ["a (x)"]

b_dict = {v.split(' ')[0]: v for v in b}

a = [b_dict.get(i, i) for i in a]

# ['a (x)', 'b']
Sign up to request clarification or add additional context in comments.

2 Comments

This seems good but I need it to keep going if there is "b (x)" in list b and so on.. What I posted what just an example
This will still work if you had "b (x)" in list b.

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.