0

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.

2
  • 1
    They are not arrays. They are lists. Commented Jul 5, 2020 at 8:00
  • 1
    @ DYZ my bad. C habits. Commented Jul 5, 2020 at 8:38

2 Answers 2

2

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]
Sign up to request clarification or add additional context in comments.

2 Comments

For the first solution, is it possible to return the index of b rather than True or False. Assume all elements could be found and you don't have address can't find anything behaviour.
Everything is possible.
2

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])

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.