Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an array is in another array in Python

I thought that in would be good for this but it returns true in places where it shouldn't. For example:

import numpy as np

a = np.array([])

for i in range(3):
    for j in range(3):
        a = np.append(a,[i,j])
a = np.reshape(a,(9,2))
print(a)

print([[0,40]] in a)

will print true. I cannot understand why it does this... is it because 0 is in the list? I'd like to have something that only prints true if the entire array is in the list.

I want to have my list

[[0,1],
[0,2]]

and only return true if exactly [0,x] (same shape same order) is in it.

like image 624
David Hambraeus Avatar asked Jun 10 '18 10:06

David Hambraeus


People also ask

How do you check if an array is in another array?

Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array. Use the inbuilt function includes() with second array to check if element exist in the first array or not. If element exist then return true else return false.

How do you compare two arrays in Python?

Method 1: We generally use the == operator to compare two NumPy arrays to generate a new array object. Call ndarray. all() with the new array object as ndarray to return True if the two NumPy arrays are equivalent.

How do I check if two arrays are equal in Python?

Check if two arrays are equal or not using SortingSort both the arrays. Then linearly compare elements of both the arrays. If all are equal then return true, else return false.

How do you know if an element is in the same array?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.


1 Answers

You can do it this way:

([0, 40] == a).all(1).any()

The first step is to compute a 2D boolean array of where the matches are. Then you find the rows where all elements are true. Then you check if any rows are fully matching.

like image 194
John Zwinck Avatar answered Sep 28 '22 16:09

John Zwinck