colt.exe
colt.exe

Reputation: 728

Check whether array elements of array are present in another array in python

I have two arrays as:

a = [[1,2,3,4],[3,1,2,4],[4,3,1,2],...] and b = [[4,1,2,3],[1,2,3,4],[3,2,4,1]....]

I want to return a True for every row element of a if it is found in b. For the visible part of the above example the result should be c = [True, False, False]. Numpy solution is welcomed.

Upvotes: 0

Views: 203

Answers (2)

theletz
theletz

Reputation: 1795

You can use numpy for this:

import numpy as np
a = np.array([[1,2,3,4],[3,1,2,4],[4,3,1,2]])
b = np.array([[4,1,2,3],[1,2,3,4],[3,2,4,1]])    
(a[:, None] == b).all(-1).any(-1)

out: array([ True, False, False])

Upvotes: 2

DYZ
DYZ

Reputation: 57033

The most naive solution:

[(x in b) for x in a]
#[True, False, False]

A more efficient solution (works much faster for large lists because sets have constant lookup time but lists have linear lookup time):

set_b = set(map(tuple, b)) # Convert b into a set of tuples
[(x in set_b) for x in map(tuple,a)]
#[True, False, False]

Upvotes: 2

Related Questions