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?
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]
[i for i, (a,b) in enumerate(zip(vec1,vec2)) if a==b]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With