Is there anyway to user map on a list with one fixed parameter without a for loop? for example
def addx(x, y):
return x + y
print map(addx, 10, [10,20])
output should be 20 and 30
Thanks
Is there anyway to user map on a list with one fixed parameter without a for loop? for example
def addx(x, y):
return x + y
print map(addx, 10, [10,20])
output should be 20 and 30
Thanks
functools.partial()
to the rescue:
from functools import partial
map(partial(addx, 10), [10, 20])
Demo:
>>> from functools import partial
>>>
>>> def addx(x, y):
... return x + y
...
>>> map(partial(addx, 10), [10, 20])
[20, 30]
You can use the lambda
anonymous-function creator to inline a new function with only one argument:
Python 2.7.10 (default, Aug 22 2015, 20:33:39)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def addx(x,y):
... return x+y
...
>>> map(lambda x: addx(x,10), [10, 20])
[20, 30]
>>>
You can also use list comprehensions:
def addx(x, y):
return x + y
print [addx(10, i) for i in [10,20]]
You can also use repeat
from itertools
:
from itertools import repeat
def addx(x, y):
return x + y
map(addx, repeat(10), [10,20])
Side note:
if you are using Executor.map()
from ProcessPoolExecutor
, it's likely to get into trouble with a lambda method, as the passed function to map
should be a top-level module function to be picklable:
https://stackoverflow.com/a/8805244/3366323