user1342516
user1342516

Reputation: 539

compare two lists in python and return indices of matched values

For two lists a and b, how can I get the indices of values that appear in both? For example,

a = [1, 2, 3, 4, 5]
b = [9, 7, 6, 5, 1, 0]

return_indices_of_a(a, b)

would return [0,4], with (a[0],a[4]) = (1,5).

Upvotes: 20

Views: 47020

Answers (4)

Ahmad Akel Omar
Ahmad Akel Omar

Reputation: 347

you can do it like this,with no need to set :

a = [1, 2, 3, 4, 5]
b = {9, 7, 6, 5, 1, 0}
[i for i, item in enumerate(a) if item in b]

inspired by @jamylak

Upvotes: 0

user4952560
user4952560

Reputation:

For larger lists this may be of help:

for item in a:
index.append(bisect.bisect(b,item))
    idx = np.unique(index).tolist()

Be sure to import numpy.

Upvotes: 3

jamylak
jamylak

Reputation: 133744

The best way to do this would be to make b a set since you are only checking for membership inside it.

>>> a = [1, 2, 3, 4, 5]
>>> b = set([9, 7, 6, 5, 1, 0])
>>> [i for i, item in enumerate(a) if item in b]
[0, 4]

Upvotes: 28

pts
pts

Reputation: 87401

def return_indices_of_a(a, b):
  b_set = set(b)
  return [i for i, v in enumerate(a) if v in b_set]

Upvotes: 6

Related Questions