Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of maximum values of columns in a matrix (without 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.

Here is my code:

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)

And here is the wanted output:

[12, 9, 18, 6]
like image 444
ithilquessirr Avatar asked Oct 29 '18 12:10

ithilquessirr


1 Answers

Python has a built-in zip which allows you to transpose1 your list of lists:

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]

1 The official description for what zip does:

Make an iterator that aggregates elements from each of the iterables.

like image 161
jpp Avatar answered Oct 18 '22 22:10

jpp