Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify index of all elements in a list comparing with another list

For instance I have a list A:

A = [100, 200, 300, 200, 400, 500, 600, 400, 700, 200, 500, 800]

And I have list B:

B = [100, 200, 200, 500, 600, 200, 500]

I need to identify the index of elements in B with comparison to A

I have tried:

list_index = [A.index(i) for i in B]

It returns:

[0, 1, 1, 5, 6, 1, 5]

But what I need is:

[0, 1, 3, 5, 6, 9, 10]

How can I solve it?

like image 257
narashimhaa Kannan Avatar asked Jul 25 '21 16:07

narashimhaa Kannan


People also ask

How do you find the index of an element in a list of lists?

By using the list. index() method, we can easily get the element index value from list. In this example we have define a list of integer values and uses the list. index() method we can get the index of the item whose value is '210'.

Can you find all indexes of an element in a list?

However, because Python lists can contain duplicate items, it can be helpful to find all of the indices of an element in a list. Let’s get started! Before diving into how to get the index positions of all elements in a Python list, let’s take a quick moment to understand how Python lists are indexed.

How to get the indices of all occurrences of an element?

Given a list, the task is to write a Python Program to get the indices of all occurrences of an element in a list. This is a simple method to get the indices of all occurrences of an element in a list. Here we use a for-loop to iterate through each element in the original list. Instead of using for-loop we can use enumerate function.

How do you use index() method in a list?

It takes two optional arguments which are indices at which search has to start and stop in the list. If the input element exists in the list between the specified indices, the index() method returns the index of the element where it occurs first. We can observe this in the following example.

How many indices of 2 are there in a list?

Output: List is: [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 46, 67, 23] Number is: 2 Indices of 2 are [1, 8] Conclusion In this article, we have used different ways to find the indices of an element in a list.


Video Answer


1 Answers

You can iterate through the enumeration of A to keep track of the indices and yield the values where they match:

A = [100,200,300,200,400,500,600,400,700,200,500,800]
B = [100,200,200,500,600,200,500]

def get_indices(A, B):
    a_it = enumerate(A)
    for n in B:
        for i, an in a_it:
            if n == an:
                yield i
                break
            
list(get_indices(A, B))
# [0, 1, 3, 5, 6, 9, 10]

This avoids using index() multiple times.

like image 172
Mark Avatar answered Sep 27 '22 22:09

Mark