2

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"]))
1
  • Have you considered using a lambda? Commented Aug 31, 2017 at 11:23

3 Answers 3

7

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, good idea mentioned list comps. That really is the better, more pythonic way in this case. +1
5

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.

1 Comment

Ah, this is also a nice idea. I forgot about functools.partial. +1
4

If you need to pass arguments to int, you'll need to wrap it in a function. You can use a normal function:

def func(i):
    return int(i, 2)

Or you can use a lambda function definition instead:

lambda i: int(i, 2)

Your code would then be:

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

However, as @Jean said, once you reach this point, you should seriously consider using a comprehension over map and lambda.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.