Issue
I am trying to locate the positions of indices of list B
: (0,2),(2,1)
with respect to list A
. But there is an error. The desired output is attached.
import numpy
A=[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
B=[(0,2),(2,1)]
C=B.index(A)
print("C =",C)
The error is
<module>
C=B.index(A)
ValueError: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] is not in list
The desired output is
[3,8]
Solution
To get the indices of the wanted pairs, you can do:
a=[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
b=[(0,2),(2,1)]
c=[a.index(b_item) for b_item in b]
print("C =", c)
This will print [2,7] (indices starting from 0). Alternatively, if you want indices starting from 1 as output (result [3,8]):
a=[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
b=[(0,2),(2,1)]
c=[a.index(b_item)+1 for b_item in b]
print("C =", c)
Note that this will result in an error if the pair is not in list a. You can work with try
and except ValueError
if you want to avoid errors.
Answered By - Olli
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.