Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python map() on zipped object

I have two inputs lists a and b and a function which takes two inputs, let's say

def f(x, y): return x*y

How do I use map() for this setup? I tried

map(f, zip(a,b))

and got

TypeError: f() takes exactly 2 arguments (1 given)

It makes sense because I need to unpack the zipped input. How can I do that?

like image 453
nos Avatar asked Dec 01 '16 13:12

nos


1 Answers

map doesn't unpack the iterables as your function argument, but instead as a more general way for dealing with such problems you can use starmap() function from itertools module which should be used instead of map() when argument parameters are already grouped in tuples from a single iterable:

from itertools import starmap

starmap(f, zip(a,b))

Here is an example:

In [2]: a = range(5)

In [3]: b = range(5, 10)

In [7]: from itertools import starmap

In [8]: list(starmap(f, zip(a,b)))
Out[8]: [0, 6, 14, 24, 36]

As another option your can just pass the iterables to map separately without zipping them.

In [13]: list(map(mul, a, b))
Out[13]: [0, 6, 14, 24, 36]

Also as a more pythonic way for multiplying two variable you can use operator.mul() instead of creating a custom function:

In [9]: from operator import mul

In [10]: list(starmap(mul, zip(a,b)))
Out[10]: [0, 6, 14, 24, 36]

Here is the benchmark:

In [11]: %timeit list(starmap(mul, zip(a,b)))
1000000 loops, best of 3: 838 ns per loop

In [12]: %timeit list(starmap(f, zip(a,b)))
1000000 loops, best of 3: 1.05 µs per loop
like image 103
Mazdak Avatar answered Sep 21 '22 01:09

Mazdak