How to use round in lambda function

Asked

Viewed 59 times

0

I want to understand how I can include the round in the following role:

lstNumerosF = [10.01, 7.03, 2.23]


lstMapa = list(map(lambda x: x ** 2, lstNumerosF))

print(lstMapa)

I wanted to use inside the lambda function the round to round the elements to 3 decimal places.

  • 2

    It’s not just doing lambda x: round(x ** 2, 3)?

  • That’s right! Thank you very much! It helped me a lot!

1 answer

1


If you want to call round within the lambda, just do this:

lstNumerosF = [10.01, 7.03, 2.23]
lstMapa = list(map(lambda x: round(x ** 2, 3), lstNumerosF))
print(lstMapa) # [100.2, 49.421, 4.973]

But in your case you may not even need map and lambda, just use a comprehensilist on:

lstNumerosF = [10.01, 7.03, 2.23]
lstMapa = [ round(x ** 2, 3) for x in lstNumerosF ]
print(lstMapa) # [100.2, 49.421, 4.973]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.