Home > Back-end >  How to check if a list of one numpy array contains another numpy array
How to check if a list of one numpy array contains another numpy array

Time:07-27

For example, I want, given the list given_list = [np.array([1,44,21,2])] Check if this list contains another numpy array, for example np.array([21,4,1,21])

I tried this but it checks if each element of the numpy array is the equal to the new numpy array

import numpy as np
given_list = [np.array([1,44,21,2])]
new_elem = np.array([21,4,1,21])

print([new_elem==elem for elem in given_list])

I would like to receive '[False]', but instead I get '[array([False, False, False, False])]'.

I don't understand why given_list is identified as a numpy array and not as a list of one numpy array.

CodePudding user response:

You can use numpy.array_equal:

[np.array_equal(new_elem, elem) for elem in given_list]

or numpy.allclose if you want to have some tolerance:

[np.allclose(new_elem, elem) for elem in given_list]

output: [False]

CodePudding user response:

If you are sure that your arrays have the same length you can do this task without cycling the elements of given_list. For example:

given_list = [np.array([1,44,21,2]), np.array([21,4,1,21])]
new_elem = np.array([21,4,1,21])

(np.array(given_list)==new_elem).all(axis=1) #array([False,  True])

Otherwise, you can use the @mozway 's [np.array_equal(new_elem, elem) for elem in given_list]

  • Related