7

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.

4

4 回答 4

5

一方面,如果您将函数映射到 a 上range,则没有参数是可迭代的。

对于您的问题,您可以使用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]

要绑定任何位置参数,请使用 hkpeprah 的答案中所述的 lambda 表达式。

于 2013-06-04T18:07:21.293 回答
3

如果您提前知道参数,则可以使用类似的 lambda

f = lambda lst: func(2,3,lst)
map(f, range(20))

或者,如果您不知道参数,您可以包装一个 lambda 表达式

f = lambda x: lambda y: lambda lst: func(x,y,lst)
f = f(2)
f = f(3)
map(f, range(20))
于 2013-06-04T18:11:42.590 回答
1

你可以使用闭包:

def initFunction(g, h):
    def funct(value):
        return g * h * value
    return funct

myFunct = initFunction(g, h)
mapped = map(myFunct, range(20)) 

PS。我猜你正在为此使用 python 3.x,否则 xrange + 生成器理解会比 range 大值好得多!(2.7 btw 中的等效代码):

def initFunction(g, h):
    def funct(value):
        return g * h * value
    return funct

myFunct = initFunction(g, h)
mapped = (myFunct(i) for i in xrange(20)) 
于 2013-06-04T19:11:17.497 回答
0

也许不是最优雅的,但您可以制作gh迭代,然后将它们直接传递给 map 函数:

## the original function: 
def func(g,h,i):
    return i*(g+h)

## define some values
g1 = 2
h1 = 5
iterable1 = list(range(10))

## make g and h iterable
g1_iter = [g1] * len(iterable1)
h1_iter = [h1] * len(iterable1)

print(list(map(func, g1_iter, h1_iter, iterable1)))

于 2021-01-21T15:18:55.670 回答