iTayb
iTayb

Reputation: 12743

Using map function with a multi-variable function

I have a multi-variable function and i would like to use the map() function with it.

Example:

def f1(a, b, c):
    return a+b+c
map(f1, [[1,2,3],[4,5,6],[7,8,9]])

Upvotes: 6

Views: 4038

Answers (3)

reclosedev
reclosedev

Reputation: 9502

itertools.starmap made for this:

import itertools

def func1(a, b, c):
    return a+b+c

print list(itertools.starmap(func1, [[1,2,3],[4,5,6],[7,8,9]]))

Output:

[6, 15, 24]

Upvotes: 10

MAK
MAK

Reputation: 26586

You can simply wrap your multi-argument function inside another function that takes just one argument as a tuple/list and then passes it on to the inner function.

map(lambda x: func(*x), [[1,2,3],[4,5,6],[7,8,9]])

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

You can't. Use a wrapper.

def func1(a, b, c):
    return a+b+c

map((lambda x: func1(*x)), [[1,2,3],[4,5,6],[7,8,9]])

Upvotes: 5

Related Questions