Replacing elements from list of lists when it matches elements from other list

Question:

a = [1,2,3,4,5]

b = [[3,4],[4,5],[6,7]]

I have two lists above.
I want to compare elements of each list from list b with elements of list a, a new list is to be formed which will be a list of lists replacing the unmatched elements with ‘X.

So the output should be a new list of lists of length same as list b as below.

c = [['X','X',3,4,'X'],['X','X','X',4,5],['X','X','X','X','X']]

Thanks.

I tried the answer in this link

However it only works if there are only two lists to compare, and I want to compare a list of lists with a list.

Asked By: Jazz365

||

Answers:

I would use a nested list comprehension:

a = [1, 2, 3, 4, 5]
b = [[3, 4], [4, 5], [6, 7]]

out = [[x if x in s else 'X' for x in a]
       for s in map(set, b)]

Output:

[['X', 'X', 3, 4, 'X'],
 ['X', 'X', 'X', 4, 5],
 ['X', 'X', 'X', 'X', 'X']]
Answered By: mozway