Home > OS >  loop through matrix using map() function in python
loop through matrix using map() function in python

Time:08-26

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

CodePudding user response:

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

CodePudding user response:

Without using numpy

If using a for in a list comphrehension still matches your question:

matrix = [[1, 2], [3, 4]]
map(
  lambda row: [print(c >= max(row), end=" ") for c in row] and print(),
  matrix
)

We can make this statement even a bit more cryptic by also removing the list comprehension:

matrix = [[1, 2], [3, 4]]
a = list(map(
  lambda row: 
    list(map(lambda c: print(c >= max(row), end=" "), row))
  and print(),
  matrix
))

While this code does not make use of a for loop, I don't think it improves readibilty and/or performance.

  • Related