Prepare two lists (A, B). Here is $ B \ subset A $. I want to retrieve the index of A that corresponds to the subset B.
In other words
A = [1\List of integers in sim 100]\\
B = [1\Even list of sim 100]\\
\Longrightarrow index = [1, 3, 5, 7..., 99]
Get an index like this.
A = list(range(1, 101))
B = list(range(2, 102, 2))
Numpy has a function that returns True for the element of A that corresponds to the subset B.
import numpy as np
isin = np.isin(A, B)
print(isin)
#array([False, True, False, True, False, True, False, True, False...
print(len(isin) == len(A))
#True
There was also a function in Numpy that returned the index of the True element.
index = list(np.where(isin))[0]
print(index)
#array([ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33...
I was able to implement it.
Prepare A given a random number and B obtained from it at random.
A = random.sample(range(1, 100), k=5)
B = random.sample(A, 3)
print(A)
#[37, 24, 76, 55, 52]
print(B)
#[55, 76, 37]
index = list(np.where(np.isin(A, B)))[0]
print(index)
#array([0, 2, 3])
I was able to get it randomly.
I was able to get the index, but it was sorted. In other words, the index that considers the order of B cannot be obtained as the first element of B is the number element of A. You can check each one with the for statement, but in the case of large lengths A and B, the amount of calculation becomes very large. So you will have to think of another way.
Recommended Posts