在二维数组中查找最大值

时间:2021-06-07 13:02:22

I'm trying to find an elegant way to find the max value in a two-dimensional array. for example for this array:

我试图找到一种优雅的方法来找到二维数组中的最大值。例如对于这个数组:

[0, 0, 1, 0, 0, 1] [0, 1, 0, 2, 0, 0][0, 0, 2, 0, 0, 1][0, 1, 0, 3, 0, 0][0, 0, 0, 0, 4, 0]

I would like to extract the value '4'. I thought of doing a max within max but I'm struggling in executing it.

我想提取值'4'。我想在最大值内做一个最大值,但我正在努力执行它。

3 个解决方案

#1


7  

Max of max numbers (map(max, numbers) yields 1, 2, 2, 3, 4):

最大数量的最大值(地图(最大值,数字)产生1,2,2,3,4):

>>> numbers = [0, 0, 1, 0, 0, 1], [0, 1, 0, 2, 0, 0], [0, 0, 2, 0, 0, 1], [0, 1, 0, 3, 0, 0], [0, 0, 0, 0, 4, 0]

>>> map(max, numbers)
<map object at 0x0000018E8FA237F0>
>>> list(map(max, numbers))  # max numbers from each sublist
[1, 2, 2, 3, 4]

>>> max(map(max, numbers))  # max of those max-numbers
4

#2


2  

Not quite as short as falsetru's answer but this is probably what you had in mind:

不像falsetru的答案那么短,但这可能是你想到的:

>>> numbers = [0, 0, 1, 0, 0, 1], [0, 1, 0, 2, 0, 0], [0, 0, 2, 0, 0, 1], [0, 1, 0, 3, 0, 0], [0, 0, 0, 0, 4, 0]
>>> max(max(x) for x in numbers)
4

#3


0  

Another way to solve this problem is by using function numpy.amax()

解决此问题的另一种方法是使用函数numpy.amax()

>>> import numpy as np
>>> arr = [0, 0, 1, 0, 0, 1] , [0, 1, 0, 2, 0, 0] , [0, 0, 2, 0, 0, 1] , [0, 1, 0, 3, 0, 0] , [0, 0, 0, 0, 4, 0]
>>> np.amax(arr)

#1


7  

Max of max numbers (map(max, numbers) yields 1, 2, 2, 3, 4):

最大数量的最大值(地图(最大值,数字)产生1,2,2,3,4):

>>> numbers = [0, 0, 1, 0, 0, 1], [0, 1, 0, 2, 0, 0], [0, 0, 2, 0, 0, 1], [0, 1, 0, 3, 0, 0], [0, 0, 0, 0, 4, 0]

>>> map(max, numbers)
<map object at 0x0000018E8FA237F0>
>>> list(map(max, numbers))  # max numbers from each sublist
[1, 2, 2, 3, 4]

>>> max(map(max, numbers))  # max of those max-numbers
4

#2


2  

Not quite as short as falsetru's answer but this is probably what you had in mind:

不像falsetru的答案那么短,但这可能是你想到的:

>>> numbers = [0, 0, 1, 0, 0, 1], [0, 1, 0, 2, 0, 0], [0, 0, 2, 0, 0, 1], [0, 1, 0, 3, 0, 0], [0, 0, 0, 0, 4, 0]
>>> max(max(x) for x in numbers)
4

#3


0  

Another way to solve this problem is by using function numpy.amax()

解决此问题的另一种方法是使用函数numpy.amax()

>>> import numpy as np
>>> arr = [0, 0, 1, 0, 0, 1] , [0, 1, 0, 2, 0, 0] , [0, 0, 2, 0, 0, 1] , [0, 1, 0, 3, 0, 0] , [0, 0, 0, 0, 4, 0]
>>> np.amax(arr)