List of maximum values of columns in a matrix (without Numpy)

Viewed 5811

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]
4 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.

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

The code with comments:

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]

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))

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).

One approach is to iterate over rows and keep maximum value on every position (column):

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)

Output:

[12, 9, 18, 6]

Another approach is first to build columns from the given list of rows and then simply find maximum in every column.

you can use this function:

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)
Related