Python 在二维数组中查找最大值
我试图找到一种在二维数组中求最大值的优雅方法。 例如,对于此阵列:Python 在二维数组中查找最大值,python,arrays,list,max,iterable,Python,Arrays,List,Max,Iterable,我试图找到一种在二维数组中求最大值的优雅方法。 例如,对于此阵列: [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,但我在执行过程中遇到了困难。max of max numbers(map(max,numbers)生成1,2,2,3,4): >>数字=[0,0,1,0,0,1]、[0,1,0,2,0,0]、[0
[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,但我在执行过程中遇到了困难。max of max numbers(map(max,numbers)
生成1,2,2,3,4):
>>数字=[0,0,1,0,0,1]、[0,1,0,2,0,0]、[0,0,2,0,0,0,1]、[0,1,0,3,0,0]、[0,0,0,0,4,0]
>>>地图(最大,数字)
>>>列表(映射(最大,编号))#每个子列表的最大编号
[1, 2, 2, 3, 4]
>>>最大值(映射(最大值,数字))#这些最大值的最大值
4.
没有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
解决这个问题的另一种方法是使用函数 这个怎么样
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 = 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]]
您可以将key
参数添加到max
中,如下所示,以查找二维数组/列表中的最大值
>>> max(max(numbers, key=max))
4
那么,如何得到每个子列表中具有最大值的索引呢?在各个方面都优于公认的答案
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]]
>>> 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(numbers, key=max))
4