【问题标题】:List of maximum values of columns in a matrix (without Numpy)矩阵中列的最大值列表(没有 Numpy)
【发布时间】:2019-04-02 08:54:09
【问题描述】:

我正在尝试在没有 Numpy 的情况下获取矩阵中列的最大值列表。我正在尝试编写大量代码,但找不到想要的输出。

这是我的代码:

list=[[12,9,10,5],[3,7,18,6],[1,2,3,3],[4,5,6,2]]

list2=[]

def maxColumn(m, column):   
    for row in range(len(m)):
        max(m[row][column])  # this didn't work
        x = len(list)+1 
    for column in range(x):
        list2.append(maxColumn(list, column))

print(list2)

这是想要的输出:

[12, 9, 18, 6]

【问题讨论】:

  • 欢迎,您可以先修复缩进吗?

标签: python python-3.x matrix max


【解决方案1】:

一种方法是遍历行并在每个位置(列)上保持最大值:

lst = [[12, 9, 10, 5], [3, 7, 18, 6], [1, 2, 3, 3], [4, 5, 6, 2]]

answer = lst[0]
for current in lst[1:]:
    answer = [max(x, y) for x, y in zip(answer, current)]

print(answer)

输出:

[12, 9, 18, 6]

另一种方法是首先从给定的行列表构建列,然后简单地在每一列中找到最大值。

【讨论】:

    【解决方案2】:

    首先,切勿将列表命名为list,因为它会使python 的list 数据结构在下游代码中无用。

    带有cmets的代码:

    my_list=[[12,9,10,5],[3,7,18,6],[1,2,3,3],[4,5,6,2]]
    
    def maxColumn(my_list):
    
        m = len(my_list)
        n = len(my_list[0])
    
        list2 = []  # stores the column wise maximas
        for col in range(n):  # iterate over all columns
            col_max = my_list[0][col]  # assume the first element of the column(the top most) is the maximum
            for row in range(1, m):  # iterate over the column(top to down)
    
                col_max = max(col_max, my_list[row][col]) 
    
            list2.append(col_max)
        return list2
    
    print(maxColumn(my_list))  # prints [12, 9, 18, 6]
    

    另外,虽然你特别提到了一个无 numpy 的解决方案,但在 numpy 中它就像这样简单:

    list(np.max(np.array(my_list), axis=0))
    

    这只是说,将my_list 转换为 numpy 数组,然后沿列找到最大值(axis=0 表示您在数组中从上到下移动)。

    【讨论】:

      【解决方案3】:

      Python 有一个内置的zip,它允许您转置1您的列表列表:

      L = [[12,9,10,5], [3,7,18,6], [1,2,3,3], [4,5,6,2]]
      
      def maxColumn(L):    
          return list(map(max, zip(*L)))
      
      res = maxColumn(L)
      
      [12, 9, 18, 6]
      

      1zip 的官方描述:

      创建一个迭代器,聚合来自每个可迭代对象的元素。

      【讨论】:

        【解决方案4】:

        你可以使用这个功能:

        def max_col(my_list):
        
        result = []
        i = 0
        
        while i < len(my_list[0]):
        
            max_val = my_list[0][i]
            j = 1
        
            while j < len(my_list):
        
                if my_list[j][i] > max_val:
                    max_val = my_list[j][i]
        
                j += 1
        
            result.append(max_val)
            i += 1
        
        return(result)
        

        【讨论】:

          猜你喜欢
          • 2013-03-17
          • 2021-07-27
          • 2021-11-26
          • 2020-02-24
          • 2012-03-28
          • 2021-10-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多