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
?
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 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
.