Reputation: 59
I have two lists. I want to get matching indices. I have come up with the following to illustrate as an example:
a = [1,2,6,5,3,4]
b = [1,3,4,2,5,6]
for i in range(len(a)):
for j in range(len(b)):
if b[j] != a[i]:
next
else:
print(i, j)
Seems fairly straightforward, but a bit long. Can anyone help me make this code more efficient?
Output:
0 0
1 3
2 5
3 4
4 1
5 2
Upvotes: 0
Views: 44
Reputation: 254
a = [1,2,6,5,3,4]
b = [1,3,4,2,5,6,1,2,3,4,5,6]
b_dict = {}
for i, n in enumerate(b):
if n not in b_dict:
b_dict[n] = []
b_dict[n].append(i)
for i in range(len(a)):
if a[i] in b_dict:
for index in b_dict[a[i]]:
print(i, index)
O(a+b) solution, since "in" in a dict is O(1)
update verion allow match duplicate number in b
Upvotes: 3
Reputation: 32997
Tips
enumerate
instead of range(len())
and indexing.if b[j] != a[i]
).>>> for i, v0 in enumerate(a):
... for j, v1 in enumerate(b):
... if v0 == v1:
... print(i, j)
...
0 0
1 3
2 5
3 4
4 1
5 2
As a list comprehension:
>>> [(i, j) for i, v0 in enumerate(a) for j, v1 in enumerate(b) if v0 == v1]
[(0, 0), (1, 3), (2, 5), (3, 4), (4, 1), (5, 2)]
(I outputted tuples cause they seem to make more sense in this context.)
Upvotes: 1
Reputation: 1290
You could use a list comprehension like so:
>>> a = [1,2,6,5,3,4]
>>> b = [1,3,4,2,5,6]
>>>
>>> [[i,j] for i,k in enumerate(a) for j,v in enumerate(b) if k==v]
[[0, 0], [1, 3], [2, 5], [3, 4], [4, 1], [5, 2]]
Upvotes: 2