Given the following function f with two arguments, what is the standard way to apply map to only x?
def f (x,y):
print x,y
More specifically, I would like to perform the following operation with map in one line.
list=[1,2,3]
fixed=10
for s in list:
f(s,fixed)
One way to do so is:
import functools
map(functools.partial(lambda x,y:f(y,x),fixed),list)
What is a better way?
Passing Multiple Arguments to map() function Suppose we pass n iterable to map(), then the given function should have n number of arguments. These iterable arguments must be applied on given function in parallel. In multiple iterable arguments, when shortest iterable is drained, the map iterator will stop.
Using the Python map() function with multiple arguments functions. Besides using the Python map() function to apply single argument functions to an iterable, we can use it to apply functions with multiple arguments.
The map function has two arguments (1) a function, and (2) an iterable.
Pass multiple arguments to the map() function in Python # Pass the handler function and the arguments to the functools. partial() method. Pass the result and the iterable to the map() function. The handler function will get called the arguments on each iteration.
First of all, there is no need to use lambda AND partial - they are alternatives:
map(lambda x:f(x,fixed),srclist)
Secondly, you could just bind the second argument with partial
, as long as you know the argument's name:
map(functools.partial(f,y=fixed),srclist)
Alternatively, use a list comprehension:
[f(x, fixed) for x in srclist]
What's wrong with:
def add(x, y):
return x + y
l = [1, 2, 3]
from functools import partial
plus10 = map(partial(add, y=10), l)
print plus10
## [11, 12, 13]
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