1

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?

Hovestar
  • 1,544
  • 4
  • 18
  • 26

3 Answers3

1

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)
Community
  • 1
  • 1
mtadd
  • 2,495
  • 15
  • 18
0

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
John
  • 13,197
  • 7
  • 51
  • 101
  • I don't quite get this code, how is it finding the index of the wanted value? – Hovestar Mar 23 '13 at 21:45
  • @Hovestar if the len of the lists are greater than the indices (i.e. `x` and `y` in this case) then it returns list[x] which is a list, and the y index from that list. Otherwise if either of the indexes are less than the length of their respective lists `None` is returned. – John Mar 23 '13 at 21:50
0

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
MostafaR
  • 3,547
  • 1
  • 17
  • 24
  • Unfortunately they aren't, I'm trying to make this solution work for as many possibilities as possible. – Hovestar Mar 23 '13 at 21:47