Kostas K
Kostas K

Reputation: 1

using python to compare lists

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?

Upvotes: 0

Views: 137

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 601659

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']

Upvotes: 2

Related Questions