Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在二维数组中查找最大值_Python_Arrays_List_Max_Iterable - Fatal编程技术网

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