查找二维数组中的最大值

问题描述 投票:0回答:8

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

[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]

我想提取值“4”。 我想过在最大范围内做最大的事情,但我在执行它时遇到了困难。

python arrays list max iterable
8个回答
42
投票

解决此问题的另一种方法是使用函数 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)

41
投票

最大数字中的最大值(

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

12
投票

不像 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

5
投票
>>> 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]

您可以将

key
参数添加到
max
中,如下所示,以查找二维数组/列表中的最大值

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

4
投票

这个怎么样?

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

1
投票

获取最大值索引和最大值的一个非常简单的解决方案可能是:

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]]

0
投票

这种方法不像其他方法那么直观,但就是这样,

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"

0
投票

chain.from_iterable
是一个优雅的解决方案:

from itertools import chain
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]
res = max(chain.from_iterable(numbers)) # 4
© www.soinside.com 2019 - 2024. All rights reserved.