Thursday, July 20, 2006

Finding indices of multidimensional arrays in python

Python is great for a lot of things. Unfortunately, there is no easy direct way to find indices of multidimensional arrays.
Example - You have a list(or array) A[5][5]. It is represented as [ [1,1,1,1,1], [2,34,23,1,4]....[1,34,54,44.1]] in python.
If you want to find the minimum in the list and find indices of the list, you have to proceed as follows:

mintest = 100000 # Some large number
# Instead of '4' in the below for loop, you can use the length attribute of the array.
for iter in range(0,4):
    min1 = min(A[iter])
    if (mintest > min1):
        row_index = citer
        col_index = A[iter][:].index(min(A[iter]))
        mintest = min1
print "Row, column indices of the minimum value %d in the array are %d,%d" % (mintest, row_index, col_index)


1 comment:

Anonymous said...

This code is more "pythonesque":

def find_2d_min(a):
(min, loc) = (a[0][0], [0, 0])
for (i, v) in enumerate(a):
for (j, w) in enumerate(v):
if w < min:
(min, loc) = (w, [i, j])
return (min, loc)

Tushar