Python 将不可iterable变量传递给使用map()计算的函数

Python 将不可iterable变量传递给使用map()计算的函数,python,map,parallel-processing,ipython,Python,Map,Parallel Processing,Ipython,我正在使用python并尝试转换具有以下结构的函数: def func(g,h,iterable): return iterable*(g+h) for iterable in range(20): print func(2,3,iterable) 转换为映射函数: def func(g,h,iterable): return iterable*(g+h) print map(func,2,3,range(20)) #does not work... ## the origina

我正在使用python并尝试转换具有以下结构的函数:

def func(g,h,iterable):
 return iterable*(g+h)

for iterable in range(20):
  print func(2,3,iterable)
转换为映射函数:

def func(g,h,iterable):
 return iterable*(g+h)

print map(func,2,3,range(20)) #does not work...
## 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)))

我遇到的问题是通过
map()
函数传递常量,目前我不知道如何做

我想要这种结构,这样我就可以轻松地使用Ipython并行工具

假设:

  • 所有iterables的实际功能完成需要约1.5小时(因此需要使用并行
    map()
    功能
  • 该函数很复杂,无法使用列表理解

本质上,如果这还不明显的话,我是一个跳转到python的MATLAB程序员,正在寻找MATLAB中的
parfor
函数的好替代品。

首先,如果你将你的函数映射到
范围内,没有参数是可移植的

对于您的问题,您可以使用将位置参数(从左到右)绑定到函数


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

如果您提前知道参数,可以使用类似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))

您可以使用闭包:

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

myFunct = initFunction(g, h)
mapped = map(myFunct, range(20)) 
另外,我猜您使用的是Python3.x,否则xrange+生成器的理解能力会比range对于大值的理解要好得多!(2.7 btw中的等效代码):


也许不是最优雅的,但您可以使
g
h
可编辑,然后将它们直接传递给map函数:

def func(g,h,iterable):
 return iterable*(g+h)

print map(func,2,3,range(20)) #does not work...
## 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)))


请注意,
partial
不能用于以任意精度指定位置参数。例如,如果要始终提供第三个参数,则必须使用其关键字,或者必须使用lambda
lambda x,y:func(x,y,const)
。太好了,托马斯的答案加上巴库留的精练,非常适合我要做的事情!