Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a conditional and lambda in map

If I want to take a list of numbers and do something like this:

lst = [1,2,4,5]
[1,2,4,5] ==> ['lower','lower','higher','higher']

where 3 is the condition using the map function, is there an easy way?

Clearly map(lambda x: x<3, lst) gets me pretty close, but how could I include a statement in map that allows me to immediately return a string instead of the booleans?

like image 989
Rob Avatar asked Jul 01 '15 05:07

Rob


People also ask

How do you use lambda and map in Python?

To work with map(), the lambda should have one parameter in, representing one element from the source list. Choose a suitable name for the parameter, like n for a list of numbers, s for a list of strings. The result of map() is an "iterable" map object which mostly works like a list, but it does not print.

How does Lambda and map functions work in Python?

Using lambda() Function with map()The map() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item.

Can lambda function be defined without ELSE clause?

Since a lambda function must have a return value for every valid input, we cannot define it with if but without else as we are not specifying what will we return if the if-condition will be false i.e. its else part.

Will the function map work on strings?

You can use the Python map() function with a String. While using the map() with a String, the latter will act like an array. You can then use the map() function as an iterator to iterate through all the string characters.


1 Answers

>>> lst = [1,2,4,5]
>>> map(lambda x: 'lower' if x < 3 else 'higher', lst)
['lower', 'lower', 'higher', 'higher']

Aside: It's usually preferred to use a list comprehension for this

>>> ['lower' if x < 3 else 'higher' for x in lst]
['lower', 'lower', 'higher', 'higher']
like image 101
John La Rooy Avatar answered Oct 31 '22 16:10

John La Rooy