Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

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

Output:

[['X', 'X', 3, 4, 'X'],
 ['X', 'X', 'X', 4, 5],
 ['X', 'X', 'X', 'X', 'X']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading