Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Apply condition in for loop to each element in a list of lists

I am trying to see if each value in array is less then 0 then output 0, else output the number itself. The output must have the same dimensions as the input. Currently the input is a 3 by 4 but output is a list. How do I get the output size the same (3 by 4 array)?

input = [[1,2,3,4],[4,5,-6,-7],[8,9,10,11]]
output= []
for i in input:
    if i < 0:
        value = 0
        output.append(value)
    else:
        value= i
        output.append(value)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Python’s NumPy arrays are a much more efficient way of dealing with nested lists. If I understood your question, your example can be simplified down to a single line:

import numpy as np
inp = np.array([[-1,2,3,4],[4,5,-6,7],[8,9,-10,11]])
print (inp)
#[[ -1   2   3   4]
# [  4   5  -6   7]
# [  8   9 -10  11]]
inp[inp < 0] = 0 
print (inp)
# [[ 0  2  3  4]
# [ 4  5  0  7]
# [ 8  9  0 11]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading