简体   繁体   English

在二维数组中查找最大值

[英]Finding the Max value in a two dimensional Array

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'.我想提取值“4”。 I thought of doing a max within max but I'm struggling in executing it.我想在最大范围内做一个最大值,但我正在努力执行它。

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)

Max of max numbers ( map(max, numbers) yields 1, 2, 2, 3, 4):最大数的最大值( map(max, numbers)产生 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

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

How about this?这个怎么样?

import numpy as np
numbers = np.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]])

print(numbers.max())

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]

You may add key parameter to max as below to find Max value in a 2-D Array/List您可以将key参数添加到max如下所示,以在二维数组/列表中查找最大值

>>> max(max(numbers, key=max))
4

One very easy solution to get both the index of your maximum and your maximum could be :获得最大值和最大值的索引的一种非常简单的解决方案可能是:

numbers = np.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]])
ind = np.argwhere(numbers == numbers.max()) # In this case you can also get the index of your max
numbers[ind[0,0],ind[0,1]]

This approach is not as intuitive as others but here goes,这种方法不像其他方法那么直观,但是在这里,

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]

maximum = -9999

for i in numbers:

    maximum = max(maximum,max(i))

return maximum"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM