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:
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?
You were close, use
enumerate() returns a tuple where first element is the index and second element is the data fetched from the iterable.
In : vec1 = [3,2,1,4,5,6,7] In : vec2 = [1,2,3,3,5,6,9] In : [i for i,(a, b) in enumerate(zip(vec1, vec2)) if a == b] Out: [1, 4, 5]