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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With