矩阵中列的最大值列表(没有 Numpy)

ith*_*irr 5 python max matrix python-3.x

我试图在没有 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)
Run Code Online (Sandbox Code Playgroud)

这是想要的输出:

[12, 9, 18, 6]
Run Code Online (Sandbox Code Playgroud)

jpp*_*jpp 5

Python 有一个内置函数zip,允许您转置列表列表

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]
Run Code Online (Sandbox Code Playgroud)

1官方描述zip

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


Dee*_*ini 2

首先,永远不要命名你的列表list,因为它会使listpython 的数据结构在下游代码中毫无用处。

带注释的代码:

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]
Run Code Online (Sandbox Code Playgroud)

另外,虽然您特别提到了非 numpy 解决方案,但在 numpy 中它就像这样简单:

list(np.max(np.array(my_list), axis=0))
Run Code Online (Sandbox Code Playgroud)

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