问题描述
在 Python 中,multiprocessing 模块可用于在一系列值上并行运行函数.例如,这会生成 f 的前 100000 次评估的列表.
In Python the multiprocessing module can be used to run a function over a range of values in parallel. For example, this produces a list of the first 100000 evaluations of f.
def f(i): return i * i def main(): import multiprocessing pool = multiprocessing.Pool(2) ans = pool.map(f, range(100000)) return ans
当 f 接受多个输入但只有一个变量变化时,是否可以做类似的事情?例如,您将如何并行化:
Can a similar thing be done when f takes multiple inputs but only one variable is varied? For example, how would you parallelize this:
def f(i, n): return i * i + 2*n def main(): ans = [] for i in range(100000): ans.append(f(i, 20)) return ans
推荐答案
有几种方法可以做到这一点.在问题中给出的示例中,您可以只定义一个包装函数
There are several ways to do this. In the example given in the question, you could just define a wrapper function
def g(i): return f(i, 20)
并将这个包装器传递给 map().更通用的方法是有一个包装器,它接受一个元组参数并将元组解包为多个参数
and pass this wrapper to map(). A more general approach is to have a wrapper that takes a single tuple argument and unpacks the tuple to multiple arguments
def g(tup): return f(*tup)
或使用等效的 lambda 表达式:lambda tup: f(*tup).
or use a equivalent lambda expression: lambda tup: f(*tup).