有沒有可能在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