Issue
I am working in python and trying to convert a function with this structure:
def func(g,h,iterable):
return iterable*(g+h)
for iterable in range(20):
print func(2,3,iterable)
Into a mapped function:
def func(g,h,iterable):
return iterable*(g+h)
print map(func,2,3,range(20)) #does not work...
The issue I am having is passing constants through the map()
function, currently I don't know how to do it.
I want this structure so I can easily use the Ipython parallelism tools.
Assume:
- The actual function completion over all iterables takes ~1.5hr (thus the desire for using a parallel
map()
function - The function is complex and cannot use list comprehension
Essentially, if it wasn't already obvious I am a MATLAB programmer making the leap to python and looking for a good substitute for the parfor
function in matlab.
Solution
For one thing, if you map your function over a range
, no parameter is an iterable.
To your question, you can bind positional parameters (from left to right) to a function using functools.partial
def func(g,h,i):
return i*(g+h)
print map(functools.partial(func, 2,3), range(20))
# [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
For binding any positional parameter, use a lambda expression like stated in hkpeprah's answer.
Answered By - Thomas Fenzl
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.