0

I have a multidimentional list called dist. I want to get the position of the max element on this list/ matrix without using NumPy. How can I do it with built-in functions? I am using Python 3.6

dist = [[    0.0,  
          1804.04,
          2120.09,
          5502.24],
        [ 1804.04,
             0.0,
          7395.44,
          5828.17]]
Michael H.
  • 3,323
  • 2
  • 23
  • 31
feys
  • 1
  • 1
  • Why without NumPy? It's so simple **and fast** using NumPy, you only have to use `np.argmax` and `np.unravel_index`. – Michael H. May 13 '17 at 10:44
  • @Michael thank you for both comment and editing. My assignment needs to be done by built-in functions. – feys May 13 '17 at 10:47
  • I found the answer: for i in range(len(dist)): for j in range(len(dist)): if dist[i][j] == max(max(dist)): max_index = (i,j) – feys May 13 '17 at 10:48

1 Answers1

0

Even though I strongly suggest NumPy (see comment below the question of OP), this one is without NumPy (only uses the built-in function enumerate and also works for ragged arrays):

dist = [[    0.0,  
          1804.04,
          2120.09,
          5502.24],
        [ 1804.04,
             0.0,
          7395.44,
          5828.17]]  # list of lists

maximum, max_line, max_col = 0, 0, 0  # !!!
for line, l in enumerate(dist):
    for col, c in enumerate(l):
        if c > maximum: maximum, max_line, max_col = c, line, col
print(maximum, max_line, max_col)

In the line marked with !!! it is assumed that only positive values are in your matrix dist (which from the name dist and its symmetry in the unedited post of OP, as well as the zero-elements on the diagonal I assumed to be plausible). Otherwise one would have to choose a smaller starting value for maximum.

Here's how it would work with NumPy (see np.argmax and np.unravel_index):

import numpy as np
dist = np.array(dist)  # array
print(np.unravel_index(np.argmax(dist), dist.shape))
Michael H.
  • 3,323
  • 2
  • 23
  • 31