DarkDrassher34
DarkDrassher34

Reputation: 59

How do I make this matching list code more efficient?

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

Answers (3)

Yukun Li
Yukun Li

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

wjandrea
wjandrea

Reputation: 32997

Tips

  1. If you have a loop that uses indices and their respective values, use enumerate instead of range(len()) and indexing.
  2. In this case you don't need to bother with the non-matching condition (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

game0ver
game0ver

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

Related Questions