Home > Back-end >  How to check if a list of pair numpy arrays is in a list
How to check if a list of pair numpy arrays is in a list

Time:06-09

I want to verify if a pair of numpy arrays is not in a list that contains pairs of numpy arrays. Example code:

x1 = np.array([1, 2, 3])
x2 = np.array([3, 1, 2])
x3 = np.array([4, 3, 2])
x4 = np.array([5, 4, 2])
pairs_list = [[x2, x1], [x3, x4], [x2, x4]]

The goal is to know if a given pair for example; [x1, x2] or [x2, x1] (positions of the pair inverted) are not (BOTH) in pairs_list.

I tried this but got an error.

[x1, x2] not in pairs_list and [x2, x1] not in pairs_list

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

However how can i use .all() if the element to be checked is a list of arrays.

CodePudding user response:

def is_in_pairs_list(arr1, arr2):
    return np.logical_or(
        (np.array([arr1, arr2])==np.array(pairs_list)).all(axis=(1,2)).any(),
        (np.array([arr2, arr1])==np.array(pairs_list)).all(axis=(1,2)).any()
    )

#TEST
is_in_pairs_list(x1, x2), is_in_pairs_list(x1, x3),\
is_in_pairs_list(x2, x4), is_in_pairs_list(x4, x2),\
is_in_pairs_list(x2, x3), is_in_pairs_list(x3, x2)

Output:

#x1,x2 x1,x3  x2,x4 x4,x2 x2,x3  x3,x2
(True, False, True, True, False, False)

the function return True if [arr1, arr2] is in pairs_list or if [arr2, arr1] is in pairs_list. So for your goal you can just use the ~ operator to invert the boolean result:

~is_in_pairs_list(x1, x2), ~is_in_pairs_list(x1, x3),\
~is_in_pairs_list(x2, x4), ~is_in_pairs_list(x4, x2),\
~is_in_pairs_list(x2, x3), ~is_in_pairs_list(x3, x2)

Output:

#x1,x2  x1,x3 x2,x4  x4,x2  x2,x3 x3,x2
(False, True, False, False, True, True)
  • Related