Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compose functions with map

Tags:

python

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?

like image 776
user3313834 Avatar asked Jul 19 '16 16:07

user3313834


People also ask

What does map () do in Python?

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.

What is composite mapping in math?

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.

What is the function of the map () syntax?

The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.

Can map function be used on strings?

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.


2 Answers

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.

like image 181
mipadi Avatar answered Oct 12 '22 04:10

mipadi


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.

like image 30
Tonechas Avatar answered Oct 12 '22 05:10

Tonechas