compare two lists in python and return indices of matched values
Asked Answered
F

4

20

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

Fasciate answered 28/4, 2012 at 19:53 Comment(2)
possible duplicate of Python: How to find list intersection?Brownstone
I don't think this question is a duplicate of that one even though it may be similar.Winters
W
28

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]
Winters answered 28/4, 2012 at 19:55 Comment(4)
Thanks a lot! What about this case: 'a = [1, 2, 9, 8]' and 'b = [1, 9, 1]' (b is a subset of a) where the desired result is '[0, 2, 0]' (the indices of a matching each value in b)? Making b a set will lose the index of the second '1' as well as the sequence of the indices.Fasciate
In that case wouldn't it be [0, 2, 0, 1, 2] or something similar? (since all the items of b occur in both lists)Winters
I haven't been clear... The resulting indices I need in this case will give array(a)[indices] = b. I've edited the question. maybe the description there is clearer.Fasciate
You should open your second case up as a new question as nobody will see it here.Winters
K
6
def return_indices_of_a(a, b):
  b_set = set(b)
  return [i for i, v in enumerate(a) if v in b_set]
Karl answered 28/4, 2012 at 19:57 Comment(0)
V
3

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.

Venesection answered 29/5, 2015 at 12:3 Comment(0)
A
0

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

Asta answered 14/2, 2023 at 9:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.