Locating index of one list with respect to another list in Python
Question:
I have lists J1
and J2
. I want to locate the index of elements of J2
with respect to J1
. For example, J2[0]=2
and this occurs at J1[1]
. Hence, the index should be 1. Similarly for other elements of J2
. I present the current and expected outputs.
import numpy as np
J1=[[1, 2, 4, 6, 7, 9, 10]]
J2=[[2, 6, 7, 9, 10]]
Indices=[i for i in J2 and J1]
print(Indices)
The current output is
[[1, 2, 4, 6, 7, 9, 10]]
The expected output is
[[1,3,4,5,6]]
Answers:
You can use index()
to find the position of an item in a list.
import numpy as np
J1=[[1, 2, 4, 6, 7, 9, 10]]
J2=[[2, 6, 7, 9, 10]]
Indices=[[J1[0].index(i) for i in J2[0]]]
print(Indices)
Output:
[[1, 3, 4, 5, 6]]
You can use the index() method to find the index in J1 for each element in J2.
Here’s the correct code:
import numpy as np
J1 = [1, 2, 4, 6, 7, 9, 10]
J2 = [2, 6, 7, 9, 10]
Indices = [J1.index(elem) for elem in J2]
print(Indices)
# output: [1, 3, 4, 5, 6]
J1.index(elem)
returns the index of elem
in J1, and then loop iterates over each element in J2.
I have lists J1
and J2
. I want to locate the index of elements of J2
with respect to J1
. For example, J2[0]=2
and this occurs at J1[1]
. Hence, the index should be 1. Similarly for other elements of J2
. I present the current and expected outputs.
import numpy as np
J1=[[1, 2, 4, 6, 7, 9, 10]]
J2=[[2, 6, 7, 9, 10]]
Indices=[i for i in J2 and J1]
print(Indices)
The current output is
[[1, 2, 4, 6, 7, 9, 10]]
The expected output is
[[1,3,4,5,6]]
You can use index()
to find the position of an item in a list.
import numpy as np
J1=[[1, 2, 4, 6, 7, 9, 10]]
J2=[[2, 6, 7, 9, 10]]
Indices=[[J1[0].index(i) for i in J2[0]]]
print(Indices)
Output:
[[1, 3, 4, 5, 6]]
You can use the index() method to find the index in J1 for each element in J2.
Here’s the correct code:
import numpy as np
J1 = [1, 2, 4, 6, 7, 9, 10]
J2 = [2, 6, 7, 9, 10]
Indices = [J1.index(elem) for elem in J2]
print(Indices)
# output: [1, 3, 4, 5, 6]
J1.index(elem)
returns the index of elem
in J1, and then loop iterates over each element in J2.