1

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()

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

This definitely works thanks. I'm wondering whether there's a simpler (less verbose) solution.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.