Search code examples
pythonfor-loopmap-function

loop through matrix using map() function in python


how to use map() instead of the following nested for loop the idea to not use for loop :)

def f(matrix):
    r, c = np.shape(array)
    for col in range(0,c): 
        for row in range(0,r): 
            if array[row][col] >= max(array[row]):
                print("true")
            else:
                print("false")

I tried to use something similar this formate but I am stuck:

print(list(map(lambda (x,y): print(x[y]) , A)))

but not working thank you :)


Solution

  • You can easily compare every element of a row to the row's max with np.where. Numpy has a built-in function which applies a 1D function along a given axis called np.apply_along_axis, which is equivalent but faster then looping over your array. Here is your solution on an example matrix with random elements:

    import numpy as np
    
    def max_comp(row):
        return np.where(row>=max(row), True, False)
    
    matrix = np.random.randint(10, size=(5,5))
    output = np.apply_along_axis(max_comp, axis=1, arr=matrix)
    print(matrix)
    print(output
    

    Out:

    [[2 3 1 4 5]
     [9 6 0 1 1]
     [9 6 3 4 1]
     [3 7 6 1 7]
     [2 1 5 7 2]]
    
    [[False False False False  True]
     [ True False False False False]
     [ True False False False False]
     [False  True False False  True]
     [False False False  True False]]