矩阵中列的最大值列表(无Numpy) [英] List of maximum values of columns in a matrix (without Numpy)

查看:149
本文介绍了矩阵中列的最大值列表(无Numpy)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在没有Numpy的矩阵中获取列的最大值列表.我正在尝试编写大量代码,但找不到所需的输出.

I'm trying to get a list of maximum values ​​of columns in a matrix without Numpy. I'm trying to write tons of codes but can't find the wanted output.

这是我的代码:

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]

推荐答案

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

Firstly, never name your lists list as it renders list data structure of python useless in the downstream code.

带注释的代码:

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中,它是如此简单:

Also, though you have specifically mentioned for a no-numpy solution, but in numpy it is as simple as this:

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

刚才说的是,将my_list转换为一个numpy数组,然后沿列查找最大值(axis = 0表示您在数组中从上到下移动).

Which just says, convert my_list to a numpy array and then find the maximum along the columns(axis=0 means you move top to down in your array).

这篇关于矩阵中列的最大值列表(无Numpy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆