Unpack Nested List For Arguments To Map()
I'm sure there's a way of doing this, but I haven't been able to find it. Say I have: foo = [ [1, 2], [3, 4], [5, 6] ] def add(num1, num2): return num1 + num2 The
Solution 1:
It sounds like you need starmap
:
>>>import itertools>>>list(itertools.starmap(add, foo))
[3, 7, 11]
This unpacks each argument [a, b]
from the list foo
for you, passing them to the function add
. As with all the tools in the itertools
module, it returns an iterator which you can consume with the list
built-in function.
From the documents:
Used instead of
map()
when argument parameters are already grouped in tuples from a single iterable (the data has been “pre-zipped”). The difference betweenmap()
andstarmap()
parallels the distinction betweenfunction(a,b)
andfunction(*c)
.
Solution 2:
try this:
foo = [
[1, 2],
[3, 4],
[5, 6]]
defadd(num1, num2):
return num1 + num2
print(map(lambda x: add(x[0], x[1]), foo))
Solution 3:
There was another answer with a perfectly valid method (even if not as readable as ajcr's answer), but for some reason it was deleted. I'm going to reproduce it, as it may be useful for certain situations
>>>map(add, *zip(*foo))
[3, 7, 11]
Post a Comment for "Unpack Nested List For Arguments To Map()"