在二维数组中查找最大值

2024-04-30 02:20:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到一种在二维数组中求最大值的优雅方法。 例如,对于此阵列:

[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”。 我曾想过在max中进行max,但我正在努力执行它


Tags: 方法数组max中求
3条回答

没有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

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

最大数的最大值(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

相关问题 更多 >