Alk
Alk

Reputation: 5557

Python Apply Function to All Elements of Array Less Than 0

I want to apply a function to all the elements of my matrix which are less than or equal to 0 which takes as an argument that element.

   my_matrix[my_matrix <= 0] = 3 * (func(my_input_here))

So for example, if we have

[0 3 5
-3 5 3
 9 2 -1]

I want to replace -3 with 3 * func(-3) and -1 with 3 * func(-1)

Upvotes: 0

Views: 93

Answers (1)

Prasad
Prasad

Reputation: 6034

I am creating a dummy function which just adds by 1. And also simulating the matrix in variable m.

m = [[0, 3, 5],
    [-3, 5, 3],
     [9, 2, -1]]

def my_func(x):
    return x + 1

m = [[element if element > 0 else 3 * my_func(element) for element in row ] for row in m] 
print(m)

Output:

[[3, 3, 5],
 [-6, 5, 3], 
[9, 2, 0]]

Upvotes: 1

Related Questions