'Fixed parameter for Map() in python
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
Solution 1:[1]
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]
Solution 2:[2]
You can also use list comprehensions:
def addx(x, y):
return x + y
print [addx(10, i) for i in [10,20]]
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | alecxe |
| Solution 2 | Safdar Iqbal |
| Solution 3 |
