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

Remove partial duplicate tuples in a list based on condition

I have a list of tuples like this:

mylist = [
    ('Apple', 'Pass'),
    ('Banana', 'Fail'),
    ('Orange', 'Pass'),
    ('Apple', 'Fail')
]

I want to remove tuple ('Apple', 'Fail') as I have ('Apple', 'Pass'), meaning remove tuple which has Fail if another tuple has Pass for Apple and so on, so the new list looks like this:

newList = [
    ('Apple', 'Pass'),
    ('Banana', 'Fail'), 
    ('Orange', 'Pass')
]

How would I do this?

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

>Solution :

Use:

# create a set to search for tuples that has Pass
pass_tuples = {e for e, s in mylist if s == 'Pass'}

# keep tuples that are Pass or doesn't have a Pass
newList = [(e, s) for e, s in mylist if s == 'Pass' or e not in pass_tuples]
print(newList)

Output

[('Apple', 'Pass'), ('Banana', 'Fail'), ('Orange', 'Pass')]

Basically you want to keep the elements in newList that are Pass or that doesn’t have a Pass.

Note: The time complexity of this approach is expected O(n).

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