Abdullah Ajmal
Abdullah Ajmal

Reputation: 148

Compare a list and a tuple containing numpy arrays

I have a python list which contains numpy arrays like:

a = [Numpy array 1, Numpy array 2, Numpy array 3]

These Numpy arrays are all 2D numpy arrays.

Now if i pick any two Numpy arrays from my list 'a' randomly and make a tuple, say,

b = (Numpy array 1, Numpy array 2)

How can i detect which arrays were picked i.e.

Numpy array 1, Numpy array 2

and which weren't i.e

Numpy array 3?

Let me repharse my question: Which numpy array from my list 'a' is not present in the tuple 'b'?

Upvotes: 1

Views: 464

Answers (1)

Code Pope
Code Pope

Reputation: 5449

You can do that by converting the numpy array to a list. Let's imagine this is your a and b:

import random
a = [np.arange(10).reshape(2,5), np.arange(10,20), np.arange(20,30)] # list of numpy arrays
first = random.randint(0,2)
second = first
while second==first:
    second = random.randint(0,2)
b = (a[first],a[second])

Now we want to know which element of a is not in the tuple b. You first convert the numpy arrays of b to list. Then you can check it with the elements of a which are also converted to list:

def arrayinList(arr, listOfArray):
    return next((True for elem in listOfArray if np.array_equal(elem, arr)), False)

missing_elem = [elem for elem in a if not arrayinList(elem,b) ]
print(missing_elem)

Upvotes: 1

Related Questions