Thursday, November 3, 2022

[FIXED] How to map a lambda function to variable that can be a float, int, or list

Issue

I'm trying to map a lambda function to variable that can be a float, int, or list.

Test #1, this works:

val = [0.1]
test =  list(map(lambda x: max(x, 1 - x), val))

Test #2, this throws TypeError: 'float' object is not iterable:

val = 0.1
test =  list(map(lambda x: max(x, 1 - x), val))

I tried to solve it with list(val) (that is, list(map(lambda x: max(x, 1 - x), list(val)))), but it throws the same error.

How can I get it to work in both Test #1 and Test #2? Python 3.7


Solution

You can handle this case using if condition inside your map function. Try like this:

val = 0.1
test = list(map(lambda x: max(x, 1 - x), val if isinstance(val, list) else [val]))

it will handle your all cases like list, int and decimal.



Answered By - Muhammad Akhlaq Mahar
Answer Checked By - Candace Johnson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.