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

Search part of tuple list

I am trying to do a list comprehension of a tuples list based on another list of tuples with partial match.

x = [((1,1),(1,1),(1,2)),
     ((2,1),(1,3),(2,9)),
     ((2,1),(2,3),(2,9))]
y = [(2,1),(1,3)]
[i for i in x for k in y if k in i]

e.g. in this x is a list of tuples & y is the desired list of tuples. If y is found in any of the items in the list of tuples in x, it should return that item.

Result is: [((2, 1), (1, 3), (2, 9)), ((2, 1), (1, 3), (2, 9)), ((2, 1), (2, 3), (2, 9))]

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

But I want only : [((2, 1), (1, 3), (2, 9))]

I tried with single tuple & it gave the desired result. But not sure why it doesn’t work when I pass a tuple list.

x = [((1,1),(1,1),(1,2)),
     ((2,1),(1,3),(2,9)),
     ((2,1),(2,3),(2,9))]
y = (2,1)
[i for i in x if y in i]

Result: [((2, 1), (1, 3), (2, 9)), ((2, 1), (2, 3), (2, 9))]

>Solution :

You can use:

x = [
    ((1, 1), (1, 1), (1, 2)),
    ((2, 1), (1, 3), (2, 9)),
    ((2, 1), (2, 3), (2, 9)),
]
y = [(2, 1), (1, 3)]

print([t for t in x if not set(y).difference(t)])

output:

[((2, 1), (1, 3), (2, 9))]

If you subtract tuples inside x from y with set operations, if all the sub tuples are present, you’ll end up with an empty set, so you want that tuple.

You could also write if set(y).issubset(t) instead of if not set(y).difference(t) part.(borrowed from @kellyBundy’s answer)

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