Reputation: 95
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?
Upvotes: 0
Views: 501
Reputation: 164673
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']
Upvotes: 4