8

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?

Tonechas
  • 13,398
  • 16
  • 46
  • 80
user3313834
  • 7,327
  • 12
  • 56
  • 99

2 Answers2

9

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.

mipadi
  • 398,885
  • 90
  • 523
  • 479
2

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.

Tonechas
  • 13,398
  • 16
  • 46
  • 80