【问题标题】:Finding the Max value in a two dimensional Array在二维数组中查找最大值
【发布时间】:2017-04-03 18:33:29
【问题描述】:

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

[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


    【解决方案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]
    

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        这个怎么样?

        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
        

        【讨论】:

        • 如何获取每个具有最大值的子列表的索引?
        【解决方案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)
        

        【讨论】:

        • 在各个方面都优于公认的答案
        • 除了它不适用于像 [[0, 1, 2], [3, 4]]这样的输入
        【解决方案5】:

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

        【讨论】:

          【解决方案6】:

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

          【讨论】:

            猜你喜欢
            • 2015-04-06
            • 2019-03-31
            • 1970-01-01
            • 1970-01-01
            • 2018-07-05
            • 2017-07-17
            • 1970-01-01
            • 1970-01-01
            • 2015-05-09
            相关资源
            最近更新 更多