Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Projecting variables in python when applying the map function

Is it possible to project the second argument of the inner function when mapping across a set of items in Python?

when using map with the monadic use of the int cast function it works simply:

list(map(int, ["4","3","1","2"]))

But I want to cast multiple binary digits to an int using int's dyadic form int("1101",2) using map:

list(map(int(,2), ["1101","0001","1100","0011"]))

2 Answers

you need lambda

list(map(lambda x : int(x,2), ["1101","0001","1100","0011"]))

but when you need list, lambda and map, that's a dead giveaway that you just need list comprehension:

[int(x,2) for x in ["1101","0001","1100","0011"]]

(clearer, shorter, and faster than map when lambda is required)

like image 84
Jean-François Fabre Avatar answered Sep 15 '26 04:09

Jean-François Fabre


The int function has signature:

int(x, base=10)

So we can make a partial, where we assign base=2 to:

from functools import partial

list(map(partial(int, base=2), ["1101","0001","1100","0011"]))

partial takes as first parameter a function (here int) as well as other (named and unnamed) parameters. It constructs a function that will fill in some parameters itself.

like image 34
Willem Van Onsem Avatar answered Sep 15 '26 02:09

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!