How to find match indices in two lists

I'm currently stuck looking for a good solution for the following list comprehension question:

It is easy to find equal values ​​with the same index in two lists, for example

>>> 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 need indexes on the lists where these matches occur, and not the values ​​themselves. Using the above example, I want: [1,4,5]

I was busy, but I could only think of a "multi-line" solution. Does anyone know how I can find indexes in a more pythonic way?

+4
source share
2 answers

You were close, use enumerate() here.

enumerate() returns a tuple where the first element is an index and the second element is data obtained from an 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] 
+7
source
 [i for i, (a,b) in enumerate(zip(vec1,vec2)) if a==b] 
+2
source

All Articles