简体   繁体   English

将变量传递给并行化函数

[英]Passing variables to parallelized function

I'm parallelizing the generation of a matrix where each element in the matrix is computed by a function fun. 我正在并行化矩阵的生成,其中矩阵中的每个元素都是由fun函数计算的。 I can get it to work if the only thing I pass into this function are the indices i and j. 如果我传递给该函数的唯一内容是索引i和j,则可以使它工作。 However, I want to pass another variable into this function say x, how do I do this? 但是,我想将另一个变量传递给该函数,例如x,该怎么办?

I'm using Python 2.7 我正在使用Python 2.7

import numpy as np                                                                  
import multiprocess as mp                                                           
import itertools                                                                    
p = mp.Pool()                                                                       

def fun((i,j)):                                                                     

   print i,j                                                                         
   prod =  i * j  
   # what if I want to have a variable x in this function
   # prod = i * j * x

   return prod                                                                       

combs = ((i,j) for i,j in itertools.product(xrange(5), repeat=2) if i <= 5)         
result = p.map(fun, combs)                                                          
p.close()                                                                           
p.join() 

newresult = np.array(result).reshape(5,5)                                           
print newresult
def fun((i,j,x)):                                                                     
   print i,j,x                                                                         
   prod =  i * j * x 
   return prod    

Why this works: You are actually just passing one object into the function, which turns out to be a tuple. 为何起作用:您实际上只是将一个对象传递给该函数,而事实证明这是一个元组。 def fun((i,j)) is just simply breaking the tuple apart again from the object. def fun((i,j))只是将元组与对象再次分开。 So to answer your question, you can just add another element to the tuple and it works fine. 因此,要回答您的问题,您只需在元组中添加另一个元素即可,并且效果很好。

A more visibly clear representation of what you are doing: 更清晰地表示您正在做什么:

def fun(data):
    i,j,x = data
    print i,j,x
    prod =  i * j * x
    return prod

data = (2,4,10)
print(fun(data))

Or you can do this: 或者您可以这样做:

def fun((i,j), x):
    print i,j, x
    prod =  i * j * x
    # what if I want to have a variable x in this function
    # prod = i * j * x

    return prod

print(fun((2,4), 10))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM