How to find index of element of one list in another list which includes the same elements?

Viewed 3695

I am trying to code in python this simple task (part of a bigger project):

I have two lists where the first one, let's say A = [1, 2, 3, 4, 5, 6] is sorted and the second one, let's say B = [3, 4, 1, 6, 2, 5] is not sorted. What I want to achieve is to obtain the value of the index for each element of the sorted list A in list B. For example, I want to come with the result of index i = 3 when I search for the element A[5] = 6. I have implemented in the simple way as follows:

for i in range(6):
    for j in range(6):
        if A[i] == B[j]:
            index = j

I would want to come up with a way which reduces it to only one loop instead of these two nested for loops.

4 Answers

If you know that all the values in B are unique, one way would be to create a dictionary that maps the values in B to their indices.

b_dict = {}
for i, b in enumerate(B):
    b_dict[b] = i

Then, loop over A and get all the values from b_dict.

a_indices = [b_dict[a] for a in A]

With your lists, we get

A: [1, 2, 3, 4, 5, 6]
B: [3, 4, 1, 6, 2, 5]
a_indices: [2, 4, 0, 1, 5, 3]

This solution is O(n) as opposed to the others, which are O(n^2), and will therefore be much faster on large lists.

The simplest possible solution is,

A = [1, 2, 3, 4, 5, 6]
B = [3, 4, 1, 6, 2, 5]
x= [B.index(i) for i in A]

#To store the result in a dictionary to map value and corresponding index.
a=dict(zip(A,x))

You can use the list.index() method to find the index of a specific element within a list:

indices = {}
for elem in A:
    indices[elem] = B.index(elem)
# {1: 2, 2: 4, 3: 0, 4: 1, 5: 5, 6: 3}

Try this:

for x in A:
  index = B.index(x)

Here index is the index varaible at each iteration.

To save in a dict:

indices = {}
for x in A:
  indices[x] = B.index(x)
Related