I encountered this question in one of my test for applying a new job.
Given this array :
arr = [[-1, 1, 2, -2, 6], [3, 4, -5]]
- For each element in the list, if negative value is found, we want to exclude it
- Square the remaining value
I already made an answer using normal looping
for i in arr:
for j in range(len(i)):
if i[j]>0:
asd = i[j]**2
i[j] = asd
else:
i.remove(i[j])
print(arr)
The result should be like this : [[1, 4, 36], [9, 16]]
The problem is, I have to use lambda function to deliver the question.
I tried to use nested loop with condition for lambda but it's very confusing. Any idea how to solve the problem ? Any helps will be very much appreciated.
CodePudding user response:
As you need to use lambda, you can convert what you would get as list comprehension (the most pythonic IMO):
[[x**2 for x in l if x>=0] for l in arr]
into a functional variant:
list(map(lambda l: list(map(lambda x: x**2, filter(lambda x: x>=0, l))), arr))
longer, less efficient, more cryptic, but you do have plenty of lambdas ;)
output: [[1, 4, 36], [9, 16]]
More on this topic: list comprehension vs lambda filter
CodePudding user response:
How about using a list comprehension?
list_ = [[-1, 1, 2, -2, 6], [3, 4, -5]]
result = [[n*n for n in e if n >= 0] for e in list_]
print(result)
Output:
[[1, 4, 36], [9, 16]]
CodePudding user response:
You can use lambda
like this:
arr = [[-1, 1, 2, -2, 6], [3, 4, -5]]
result = lambda nested_list: [[a ** 2 for a in b if a > 0] for b in nested_list]
print(result(arr))
>>> [[1, 4, 36], [9, 16]]
CodePudding user response:
A bit more verbose: the partial
is not required but it is a bad practice to assign lambda
to variable.
from functools import partial
power_2 = (2).__rpow__
is_positive = (0).__lt__
apply_to_row = partial(lambda row: list(map(power_2, filter(is_positive, row))))
out = list(map(apply_to_row, arr))
or a single line
out = list(map(lambda row: list(map(power_2, filter(is_positive, row))), arr))
CodePudding user response:
one way of using lambda
>>> arr = [[-1, 1, 2, -2, 6], [3, 4, -5]]
>>> function = lambda x: map(lambda j:j**2, filter(lambda y: y>0, x))
>>> result = list(map(lambda x: list(function(x)), arr))
>>> result
[[1, 4, 36], [9, 16]]