Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for array - is value contained in another array?

I'd like to return a boolean for each value in array A that indicates whether it's in array B. This should be a standard procedure I guess, but I can't find any information on how to do it. My attempt is below:

A = ['User0','User1','User2','User3','User4','User0','User1','User2','User3'
     'User4','User0','User1','User2','User3','User4','User0','User1','User2'
     'User3','User4','User0','User1','User2','User3','User4','User0','User1'
     'User2','User3','User4','User0','User1']
B = ['User3', 'User2', 'User4']
contained = (A in B)

However, I get the error:

ValueError: shape mismatch: objects cannot be broadcast to a single shape

I'm using numpy so any solution using numpy or standard Python would be preferred.

like image 717
pir Avatar asked Apr 04 '15 22:04

pir


People also ask

How to check if a value is contained in an array?

The includes method will return true if the value is contained in the array and false otherwise. The Array.includes method performs a case-sensitive check whether a value is contained in an array. Pass a function to the Array.find () method. Lowercase the array element and the string and do an equality check.

How to check if every element of the first array exists?

In this post, we will look at different ways to check if every element of the first array exists in the second array. We can use the Array.prototype.every () method (which was introduced in ES5) to check whether all elements in the array pass the test implemented by the provided function.

How does array find work in JavaScript?

The function we passed to the Array.find method gets called with each object in the array until it returns a truthy value or iterates over all the elements. On each iteration, we check if the object's id is equal to 2 and if it is, the condition is met and the object is returned from the find method.

How do you check if an array has multiple subarrays?

Simple Approach: A simple approach is to run two nested loops and generate all subarrays of the array A [] and use one more loop to check if any of the subarray of A [] is equal to the array B []. Efficient Approach : An efficient approach is to use two pointers to traverse both the array simultaneously.


1 Answers

You can use in1d I believe -

np.in1d(A,B)
like image 197
Divakar Avatar answered Sep 29 '22 16:09

Divakar