pythonpython-3.xnumpyscipykdtree

Remove entries in a python set based on condition


I used scipy.spatial.KDTree.query_pairs() which returned a python set of tuples. Let's say, this is the output:

set1 = {(2, 3), (4, 5), (1, 6), (6, 7), (3, 8), (6, 8)}

Next, I want to erase all the tuples in the set which do not fulfill the condition

arr = [6, 7]
tuple[0] in arr or tuple[1] in arr

What would be the most elegant/fast/pythonic way? Should I maybe convert to a numpy array?


Solution

  • You need to iterate over and check every tuple in set1, you can do that using a set comprehension, and any():

    >>> set1 = {(2, 3), (4, 5), (1, 6), (6, 7), (3, 8), (6, 8)}
    >>> arr = [6, 7]
    >>> set2 = set(arr)  # convert to set for O(1) lookup time
    >>> set3 = {t for t in set1 if any(x in set2 for x in t)}
    >>> set3
    {(6, 7), (6, 8), (1, 6)}