0

I have a data-array like:

all = [[1,-1], [1,0], [1,1], [2,-1], [2,0], [2,1]]  etc.

It has about 4000 pairs in it, but typically fewer on the order of a few hundred.

I need to find whether a two-valued array already exists in this large data-array, eg. does [1,1] exist in the array?

So the function I need should act something like this:

isValid( all, [1,1] )
>>> True

isValid( all, [1,100] )
>>> False

I couldn't get the numpy functions isin() or in1d() to do this for me. The one function I did find works, for lists, is:

all.index( [1,1] )
>> True

but when the arg is not in the all array, I have to try/catch a ValueError and then return False - acceptable for now, but not ideal.

3
  • 2
    Maybe [1,1] in lst? By the way, don't name your variable all, which is the name of a built-in function. I've used lst instead of all. Commented Jun 2, 2022 at 1:14
  • What does this have the do with numpy? What you've shown is a list not an array Commented Jun 2, 2022 at 1:49
  • nothing to with with numpy, apart from numpy being one module that might help - converting to array would be acceptable, as the 2nd answer does. Commented Jun 2, 2022 at 4:14

2 Answers 2

1

You can use simple array lookup like this:

a = [[1,-1], [1,0], [1,1], [2,-1], [2,0], [2,1]]

[2,0] in a # True
[2,3] in a # False

or

a.index([2,0]) # result: 4
a.index([3,5]) # throw error, use try catch
Sign up to request clarification or add additional context in comments.

Comments

1

If you have numpy installed, you can use np.where to find the indices of 1d array in a 2d numpy array and check if the return result

import numpy as np

def isValid(arr, val):
   return len(np.where(np.prod(arr == val, axis = -1))[0]) != 0

all_items = np.array([[1,-1], [1,0], [1,1], [2,-1], [2,0], [2,1]] )
search1 = isValid(all_items, [1,1] ) # True
search2 = isValid(all_items, [1,100] ) # False

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.