問題描述
在 Python 中,multiprocessing
模塊可用于在一系列值上并行運(yùn)行函數(shù).例如,這會(huì)生成 f 的前 100000 次評(píng)估的列表.
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
當(dāng) f 接受多個(gè)輸入但只有一個(gè)變量變化時(shí),是否可以做類似的事情?例如,您將如何并行化:
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
推薦答案
有幾種方法可以做到這一點(diǎn).在問題中給出的示例中,您可以只定義一個(gè)包裝函數(shù)
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)
并將這個(gè)包裝器傳遞給 map()
.更通用的方法是有一個(gè)包裝器,它接受一個(gè)元組參數(shù)并將元組解包為多個(gè)參數(shù)
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 表達(dá)式:lambda tup: f(*tup)
.
or use a equivalent lambda expression: lambda tup: f(*tup)
.
這篇關(guān)于多處理具有多個(gè)輸入的函數(shù)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!