Search code examples
pythonloopslambdanestedlogic

lambda in nested loop with condition


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

  1. For each element in the list, if negative value is found, we want to exclude it
  2. 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.


Solution

  • 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