Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]])
like image 282
iTayb Avatar asked Feb 04 '12 07:02

iTayb


People also ask

How do you take multiple inputs using map function?

To do this in pmap() , just create a list out of x and y . If you only have two input vectors, though, use map2() . If we want to apply min() to parallel elements of three vectors, we'll need to use pmap() . z is a third vector.

Can map take multiple arguments?

You can pass as many iterable as you like to map() function in Python.

How many arguments can map have?

map() takes two arguments at most. The first parameter is which function to apply to each element. This is a required parameter. The second parameter is optional and is provided with the function to be used as the this keyword.

How many arguments pass in map function?

The map function takes two arguments: an iterable and a function , and applies the function to each element of the iterable.


2 Answers

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]
like image 117
reclosedev Avatar answered Oct 16 '22 17:10

reclosedev


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]])
like image 5
Ignacio Vazquez-Abrams Avatar answered Oct 16 '22 19:10

Ignacio Vazquez-Abrams