Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the indexes of matches in two lists

I'm currently stuck in trying to find a nice solution for the following list comprehension question:

It's easy to find equal values with the same index in two lists, e.g.

>>> vec1 = [3,2,1,4,5,6,7]
>>> vec2 = [1,2,3,3,5,6,9]
>>> [a for a, b in zip(vec1, vec2) if a == b]
[2,5,6]

However, I just need the indexes in the lists where these matches occur, not the values itself. Using the above example, the output I want is: [1,4,5]

I tinkered around but I could only think of a "multi-line" solution. Does anybody know how I could find the indexes in a more Pythonic manner?

like image 813
Excalibur Avatar asked Jan 15 '23 10:01

Excalibur


2 Answers

You were close, use enumerate() here.

enumerate() returns a tuple where first element is the index and second element is the data fetched from the iterable.

In [169]: vec1 = [3,2,1,4,5,6,7]

In [170]: vec2 = [1,2,3,3,5,6,9]

In [171]: [i for i,(a, b) in enumerate(zip(vec1, vec2)) if a == b]
Out[171]: [1, 4, 5]
like image 129
Ashwini Chaudhary Avatar answered Jan 16 '23 23:01

Ashwini Chaudhary


[i for i, (a,b) in enumerate(zip(vec1,vec2)) if a==b]
like image 30
Emanuele Paolini Avatar answered Jan 17 '23 01:01

Emanuele Paolini