Is there a one line code to find maximal value in

2019-02-16 13:16发布

问题:

To find the maximal value in a matrix of numbers, we can code 5 lines to solve the problem:

ans = matrix[0][0]
for x in range(len(matrix)):
    for y in range(len(matrix[0])):
        ans = max(ans, matrix[x][y])
return ans

Is there a one line solution for this problem? The one that I came up with is pretty awkward actually:

return max(max(matrix, key=max))

or

return max(map(max, matrix))

回答1:

You can use generator expression to find the maximum in your matrix. That way you can avoid building the full list of matrix elements in memory.

maximum = max(max(row) for row in matrix)

instead of list comprehension as given in a previous answer here

maximum = max([max(row) for row in matrix])

This is from PEP (the rationale section):

...many of the use cases do not need to have a full list created in memory. Instead, they only need to iterate over the elements one at a time.

...

Generator expressions are especially useful with functions like sum(), min(), and max() that reduce an iterable input to a single value

...

The utility of generator expressions is greatly enhanced when combined with reduction functions like sum(), min(), and max().

Also, take a look at this SO post: Generator Expressions vs. List Comprehension.



回答2:

By matrix, I assume you mean a 2d-list.

max([max(i) for i in matrix])


回答3:

using numpy.amax:

import numpy as np
>>> my_array
array([[1, 2, 3],
       [9, 8, 6]])
>>> np.amax(my_array)
9


回答4:

You can also flatten your array:

from itertools import chain

flatten = chain.from_iterable

max(flatten(matrix))