Reputation: 1627
So I'm working on a project where I have a two dimensional array, and I need to find the location of an element placed on the second dimension, without knowing the index of it's first dimension.
I know that I can possibly iterate over the parts, checking to see if list[x].index(y)
isn't a value error, but that makes my code a lot less elegant looking, and I wanted to know if there's a better way to do it, like a 2d .index method?
Upvotes: 1
Views: 174
Reputation: 2555
Assuming you don't want to reinvent the wheel I believe this question has the answer you're looking for: Is there a Numpy function to return the first index of something in an array?
import numpy as np
a = np.array([[1,2,4],[4,5,6]])
item = 4
row_indices, col_indices = np.where(a == item)
Upvotes: 1
Reputation: 3695
If length of all rows are equal, you can use this code:
index_2d = [item for row in list for item in row].index(y)
index_row = index_2d / ROW_LENGTH
index_col = index_2d % ROW_LENGTH
Upvotes: 0
Reputation: 13699
Try something like this.
>>> l = [[1,2,3],[4,5],[6,7,8,9]]
>>> x = 1
>>> y = 2
>>> v = l[x][y] if len(l) > x and len(l[x]) > y else None
>>> v is None
True
Upvotes: 0