Python check if list in list of lists with numpy arrays

Question:

I want to check if my query which is of type list is in the database (a list of lists). In the example below it is.

query = [np.array([[4,3],[6,4]]),5,2,1,5]

database = [ [np.array([[8,5],[2,1]]),5,3,1,9],
             [np.array([[4,3],[6,4]]),5,2,1,5],
             [np.array([[7,2],[6,4]]),0,0,8,5]]

I have tried this:

np.any([(query==data) for data in database])

However, I get the following error:

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

||

Answers:

Try this:

query = [i.tolist() if isinstance(i, np.ndarray) else i for i in query]
print(np.any([[i.tolist() if isinstance(i, np.ndarray) else i for i in data] == query for data in database]))

Output:

True
Answered By: U12-Forward

Since np.array_equal can accept arrays or scalars, you could use it this way:

In [107]: any(all(np.array_equal(datum, q) for datum, q in zip(data, query)) for data in database)
Out[107]: True

If your scalars are floats, you may wish to use np.allclose instead of np.array_equal since testing for exact float equality is often not desireable:

In [108]: np.array_equal(0.1+0.2, 0.3)
Out[108]: False

In [109]: np.allclose(0.1+0.2, 0.3)
Out[109]: True
Answered By: unutbu

Here is a quick one-liner

np.in1d(["a","b"],["c","k","b"])

Returns

array([False,  True])

It checks if each value of the first list is in the second list and returns True or False for each.

Hope that helps.

Answered By: John
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.