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

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


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.

>Solution :

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


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

Leave a Reply