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"]))
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)
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.
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