dward4
dward4

Reputation: 1922

Check if each element in a numpy array at its given position matches another element at the same position in a different array

Given two arrays,

a = ([1,2,3])
b = ([1,3, 2])

is there an elegant way to check if any element at position i in a matches position i in b?

I know it's easy enough to loop through:

for i in range(len(a)):
    for j in range(len(b)):
        if a[i] == b[j]:
            print("There is a match")

But I am interested in more elegant or faster methods.

Thank you!

Upvotes: 0

Views: 290

Answers (1)

Reblochon Masque
Reblochon Masque

Reputation: 36652

If you like to use numpy, it offers a concise, elegant, and efficient way to do this:

import numpy as np

a = np.array([1, 2, 3, 4])
b = np.array([1, 3, 2, 4])
np.where(a==b)

The output is a tuple containing an array of indices where the elements of a are equal to the elements of b:

(array([0, 3]),)

Upvotes: 1

Related Questions