Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return index and value from array

So, the goal here is to iterate through each row of a DEM (or any spatially referenced array), find the smallest value (e.g. low point), and then return the value and the related index.

This is not elegant, but I can get the values easily enough with a loop and seed:

`lowpts=[]
low=99999
for i in range(len(DEM)):
    for j in range(len(DEM)):
        low1 = DEM[i][j]
        if low1 < low:
            low = low1
    lowpts.append(low)`

But now how do I retain the [i][j] index associated with each value?

Ideally, the return would be [[i,j,value],......]

I have tried enumerate() but not sure how to implement it correctly. And I have to be aware of possible duplicate values, so I cannot just .index the lowpts array (akin to Python: finding an element in an array).

like image 861
user1873713 Avatar asked Mar 16 '26 03:03

user1873713


1 Answers

you are giving the answer in your own question!

lowpts=[]
low=99999
for i in range(len(DEM)):
    for j in range(len(DEM)):
        low1 = DEM[i][j]
        if low1 < low:
            low = low1
            low_i = i
            low_j = j
    lowpts.append([i,j,low])
like image 138
tato Avatar answered Mar 21 '26 09:03

tato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!