Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find whether 1D sub-array is in 2D array

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 the return False – acceptable for now, but not ideal.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading