有没有可能在python中并行化下面的代码?我想知道如何将这个代码转换地图和lambda功能..在python中并行化for循环
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]
有没有可能在python中并行化下面的代码?我想知道如何将这个代码转换地图和lambda功能..在python中并行化for循环
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]
可以并行化功能,运算与多与地图:
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)
做得好!这几乎是我的想法!等待任何其他答案,以获得最简单的方法。 – PeCaDe
检查了这一点:
from itertools import permutations
values = (1,2,3,4,5)
[(i, j, i+j) for i, j in permutations(values, 2)]
它在Python的STDLIB。
如果你想在并行运行,看看这个使用python3:
import multiprocessing
from itertools import permutations
values = [1, 2, 3, 4, 5]
l = permutations(values, 2)
def f(x):
return x[0], x[1], x[0] + x[1]
with multiprocessing.Pool(5) as p:
data = p.map(f, l)
您可以使用该模块“多”:请参阅https://docs.python.org/2/library/multiprocessing.html – user2660966
也许通过使用map函数?,我在Python新手。因为迭代需要很长时间。 – PeCaDe