Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the Indices of multiple items in a list, using a list

Tags:

python

list

I want to essentially use one list ie.

L = [10, 10, 100, 10, 17, 15]

and using another list

R = [10, 15] 

want to return

N = [0, 1, 3, 5] // indices of L that return the values in R

I tried using L.index() to get the indices but that only returns the first value. I then tried running a for loop over L and using L.index(R[0]) every time, but similarly that only returns the first indices it finds at.

 for i in range(len(L)):
       j = R[i]
       N.append(L.index(j))
 return N

This would return index out of range which makes sense, but how do I get it to run through the L?

like image 943
Andre Fu Avatar asked Feb 21 '18 04:02

Andre Fu


People also ask

How do you get the indices of all occurrences of an element in a list in Python?

One of the most basic ways to get the index positions of all occurrences of an element in a Python list is by using a for loop and the Python enumerate function. The enumerate function is used to iterate over an object and returns both the index and element.


1 Answers

N = []

for i in range(len(L)):

    if L[i] in R:
        N.append(i)

or with a generator

N = [i for i in range(len(L)) if L[i] in R]

or with arrays

import numpy as np

N=np.where(np.isin(L,R))
like image 153
Demetri Pananos Avatar answered Oct 21 '22 06:10

Demetri Pananos