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)
CodePudding user response:
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]]
CodePudding user response:
You need a nested loop.
lists = [[1, 2, 3, 4], [4, 5, 6, 7], [8, 9, 10, 11]]
output = []
for l in lists:
nested_list = []
for i in l:
if i < 0:
nested_list.append(0)
else:
nested_list.append(i)
output.append(nested_list)
Also, you shouldn't name your variable input as it will override the input() function.
CodePudding user response:
you can achieve it this way -
l = [[1,2,3,4],[4,5,-6,-7],[8,9,10,11]]
res = [[x if x >= 0 else 0 for x in in_l]for in_l in l]
CodePudding user response:
You don't necessarily need to import any additional libraries for this, that would be an overkill. Base python provides all the necessary operations for handling nested data structures and conditional operations.
You can do this with a combination of list comprehension and ternary operators in python -
inp = [[1,2,3,4],[4,5,-6,-7],[8,9,10,11]]
[[0 if item<0 else item for item in sublist] for sublist in inp]
#|____________________|
# |
# ternary operator
[[1,2,3,4],[4,5,0,0],[8,9,10,11]]
A list comprehension would allow you to avoid the
list.append()and directly result in a list as output. Note, that you need a listed list comprehension since you want to iterate over elements of a list of lists.A ternary operator is a conditional expression of the form
[on_true] if [expression] else [on_false]. This lets you add conditions (if-else) to the list comprehension on each element you are iterating.
