简体   繁体   中英

An efficient way to grab the indexes for a two dimension list in python

I have this list:

my_list = [[1,2,3],
           [4,5,6],
           [7,8,9]]

And I want the index for, let's say number nine. It would be (2,2). I want an efficient and less verbose way to get the x,y indexes and I tried this:

def my_indexes(the_list):
    (i_s, j_s) = [[(i, j) for j, cell in enumerate(row) if cell == 9] for i, row in enumerate(the_list) if 9 in row][0][0]
    return (i_s, j_s)

my_indexes(my_list)
(2, 2)

It works but perhaps my approach is overcomplicated. Please, could you help me with a better approach? Thank you.

Since this is tagged numpy, I'll give you the numpy solution

np_list = np.array(my_list)                                                                                         
np.argwhere(np_list == 9)

array([[2, 2]], dtype=int64)  

You can try to use this.

n = 9
[(i, sub_list.index(n)) for i, sub_list in enumerate(my_list) if n in sub_list]

I got the output as [(2,2)] for your input.

This returns a list of tuples with indexes of all occurrences. If you need only the first occurrence you can break the iteration on the first encounter. I couldn't think of a much simpler one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM