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?

Chris Morgan
91.4k28 gold badges216 silver badges220 bronze badges
asked Nov 7, 2011 at 22:42

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']
answered Nov 7, 2011 at 22:44
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.