python - getting all the tiles with the maximum value in a 2d grid (a multidimensional list) -
i have 2d grid (multidimensional list) maybe so: [[1,2,3],[1,3,3],[1,1,1]]
, want positions of elements contain max values, in case be: (0,3), (1,1)
and(1,2)
.
i have clumsy way works, this:
max_val = -999999 in range(board.get_dim()): j in range(board.get_dim()): if scores[i][j] > max_val: max_val = scores[i][j] max_coords = [] in range(board.get_dim()): j in range(board.get_dim()): if scores[i][j] == max_val: max_coords.append((i,j))
but hoping if point me more concise solution?
one way utilize itertools.chain
max()
max value , utilize list comprehension enumerate()
indices:
>>> itertools import chain ##find max value on flattened version of list >>> max_val = max(chain.from_iterable(lst)) >>> lst = [[1,2,3], [1,3,3], [1,1,1]] >>> [(i, j) i, x in enumerate(lst) j, y in enumerate(x) if y == max_val] [(0, 2), (1, 1), (1, 2)]
numpy makes easy though:
>>> import numpy np >>> arr = np.array(lst) >>> zip(*np.where(arr==arr.max())) [(0, 2), (1, 1), (1, 2)]
python list max
No comments:
Post a Comment