PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 3, 2022

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

 November 03, 2022     dictionary, lambda, list, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing