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

Checking if a list element is inside another list if so, substitute every element inside the base list

So I currently have a bunch of mocks list such as this one. Sample:

l = ['a','a','c','d']
l2 = ['c','b','b','d']
l3 = ['c','b','b','d','x','z']
l4 = ['a','c','a','a']

What I want to do is check if any of the values inside each of these lists, is equal to any of the values inside another list.

target_l = ['a','b']

If so i want to change every element inside these lists into the matched element.

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

Wanted result:

l = ['a','a','a','a']
l2 = ['b','b','b','b']
l3 = ['b','b','b','b','b','b']
l4 = ['a','a','a','a']

>Solution :

Use a for loop to loop over all of the possible targets. When you see a match, replace all the elements and break:

for lst in [l, l2, l3, l4]:
    for target in target_l:
        if target in lst:
            lst[:] = [target] * len(lst)
            break

print(l, l2, l3, l4, sep='\n')

This outputs:

['a', 'a', 'a', 'a']
['b', 'b', 'b', 'b']
['b', 'b', 'b', 'b', 'b', 'b']
['a', 'a', 'a', 'a']
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