我在 python 3.6 中有一些代码是这样的:
from multiprocessing import Pool
with Pool(processes=4) as p:
p.starmap(parallel_function, list(dict_variables.items()))
这里 dict_variables 看起来像这样:
[('aa', ['ab', 'ab', 'ad']), ('aa1', ['a1b', 'a1b', 'a2d'])]
此代码仅适用于 python 3.6。我怎样才能让它在 2.7 中工作?
starmap
在 Python3.3中引入。在 Python2 中,Pool.map
自己使用和解压参数:
在 Python3 中:
import multiprocessing as mp
def starmap_func(x, y):
return x**y
with mp.Pool(processes=4) as p:
print(p.starmap(starmap_func, [(1,2), (3,4), (5,6)]))
# [1, 81, 15625]
在 Python2 或 Python3 中:
import multiprocessing as mp
def map_func(arg):
x, y = arg
return x**y
p = mp.Pool(processes=4)
print(p.map(map_func, [(1,2), (3,4), (5,6)]))
# [1, 81, 15625]
p.close()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句