I'm using two map calls to transform a string of '0'
s and '1'
s into a sequence of booleans:
>>> a, b = '10'
>>> a, b = map(int, (a, b))
>>> a, b = map(bool, (a, b))
>>> a, b
(True, False)
How to do that with only one map
?
Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.
A mapping is composite when the co- domain of the first mapping is the domain of the second mapping. Consider the mapping f;X→ Z and g: Z→Y. SOLUTION: (a) F(-3) + F(4) = -5 + 9 = 4.
The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.
Map() Function in Golang is used to return a copy of the string given string with all its characters modified according to the mapping function.
Python doesn't have a function composition operator, so there's not a built-in way to do that. In this specific case, the easiest way to reduce the map
call to one line is with a lambda:
a, b = map(lambda x: bool(int(x)), (a, b))
You could write a more general compose
function easily enough, and use that instead:
def compose(*fns):
return reduce(lambda f, g: lambda x: f(g(x)), fns, lambda x: x)
a, b = map(compose(bool, int), (a, b))
But to be honest, the latter method seems like overkill here.
You can get the job done in one line of code by using a list comprehension instead of map()
like this:
>>> mask = '100110110'
>>> bools = [bool(int(letter)) for letter in mask]
>>> bools
[True, False, False, True, True, False, True, True, False]
Have a look at this thread to figure out the differences between using a list comprehension and map
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With