0

I have three lists in python. The first two contain strings and the third one contains ids that match the first one.

I would like to compare the strings from the second list with all the terms from the first list and when I find the same string I want to take the id from the third list and replace the string from the second list.

e.g.

list1 = ['hello, 'bye', 'third']
list2 = ['bye', 'second', 'forth']
list3 = [100, 150, 60] 

as you can see the common term is bye. So I want to take the id from list3 (which is 150 and corresponds to the string in list1) and replace the 'bye' string from list2 with this id.

Is there an easy way to do this with python?

1 Answer 1

2

First, construct a dictionary mapping the strings in list1 to the corresponding ids. Then, use a list comprehension to apply the mapping:

list1 = ["hello", "bye", "third"]
list2 = ["bye", "second", "forth"]
list3 = [100, 150, 60] 
d = dict(zip(list1, list3))
print([d.get(x, x) for x in list2])

prints

[150, 'second', 'forth']
Sign up to request clarification or add additional context in comments.

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.