Reputation: 479
I have a 2d grid (multidimensional list) like maybe so: [[1,2,3],[1,3,3],[1,1,1]]
and I want to get the positions of all elements that contain the max values, so in this case that would be: (0,3), (1,1)
and(1,2)
.
I now have a very clumsy way which works, like this:
max_val = -999999
for i in range(board.get_dim()):
for j in range(board.get_dim()):
if scores[i][j] > max_val:
max_val = scores[i][j]
max_coords = []
for i in range(board.get_dim()):
for j in range(board.get_dim()):
if scores[i][j] == max_val:
max_coords.append((i,j))
But I was hoping if someone could point me to a more concise solution?
Upvotes: 1
Views: 1025
Reputation: 251011
One way is to use itertools.chain
with max()
to get the max value and then use a list comprehension with enumerate()
to get the indices:
>>> from itertools import chain
##find the max value on a flattened version of the list
>>> max_val = max(chain.from_iterable(lst))
>>> lst = [[1,2,3], [1,3,3], [1,1,1]]
>>> [(i, j) for i, x in enumerate(lst) for j, y in enumerate(x) if y == max_val]
[(0, 2), (1, 1), (1, 2)]
NumPy makes it very easy though:
>>> import numpy as np
>>> arr = np.array(lst)
>>> zip(*np.where(arr==arr.max()))
[(0, 2), (1, 1), (1, 2)]
Upvotes: 2