Is there a way to unpack a tuple with the * idiom when using the map built-in in Python?
Ideally, I'd like to do the following:
def foo(a, b):
return a**2 + b
x = [(1,2), (3,4), (5,6)]
results = map(foo, *x)
where results would equal [3, 13, 31]
You're looking for itertools.starmap:
def foo(a, b):
return a**2 + b
x = [(1,2), (3,4), (5,6)]
from itertools import starmap
starmap(foo, x)
Out[3]: <itertools.starmap at 0x7f40a8c99310>
list(starmap(foo, x))
Out[4]: [3, 13, 31]
Note that even in python 2, starmap returns an iterable that you have to manually consume with something like list.
An uglier way than the @roippi's way...
x = [(1,2), (3,4), (5,6)]
map(lambda y:y[0]**2 + y[1], x)
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