I want to find a specific element in the 2D list and display its location.

Asked 2 years ago, Updated 2 years ago, 123 views

2d_array=[0,0,0],[0,0,1],[0,0,0],[0,0,0]]

I would like to print the final result '(1,2)' from the list like above.

As a trial, I made a separate list, added each element to the array above, and then looked for 1, and I got the result that it was in the fifth place, but I couldn't get to (1, 2) from there.
Thank you for your cooperation.

python python3 array

2022-09-30 21:29

1 Answers

If you like to use NumPy, you can use np.where to write:This method lists all the locations where the desired element is located.

>>import numpy as np
>>arr = [[0, 0, 0], [0, 0, 1], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>>ind=np.where(np.array(arr)==1)
>>>ind
(array([1]), array([2]))
>>># or:
... (ind[0][0], ind[1][0])
(1, 2)

If you were to create a function with raw Python, for example, you could simply use a loop in to write:Here we find the first place that contains the desired element.

>>def find 2d(lst,elem):
...     for i, row in enumerate (lst):
...         for j, e in enumerate (row):
...             if == elem:
...                 return i,j
...   return-1,-1# This is what happens when there is no desired element.
... 
>>arr = [[0, 0, 0], [0, 0, 1], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>find2d(arr,1)
(1, 2)

Note, however, that both methods are misdetected if True is in the element (because in Python 3 it is True==1).


2022-09-30 21:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.