Is there any possibility to parallelize the following code in python? I was wondering how to convert this code with map and lambda functions..
values = (1,2,3,4,5 )
def op(x,y):
return x+y
[(i, j, op(i, j))
for i in values
for j in values
if i is not j]
解决方案
You can parallelize the function op with multiprocessing and map:
from multiprocessing.dummy import Pool as ThreadPool
from itertools import permutations
pool = ThreadPool(4) # Number of threads
values = (1,2,3,4,5)
aux_val = [(i, j) for i,j in permutations(values,2)]
def op(tupx):
result = (tupx[0], tupx[1], tupx[0] + tupx[1])
return result
results = pool.map(op, aux_val)