2017-04-24 94 views
1

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

您可以使用該模塊「多」:請參閱https://docs.python.org/2/library/multiprocessing.html – user2660966

+0

也許通過使用map函數?,我在Python新手。因爲迭代需要很長時間。 – PeCaDe

回答

2

可以並行化功能,運算與多與地圖:

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) 
+0

做得好!這幾乎是我的想法!等待任何其他答案,以獲得最簡單的方法。 – PeCaDe

2

檢查了這一點:

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) 
+0

這不是平行過程,不是嗎? @gushitong – PeCaDe

+1

@PeCade我已經使用python3添加了並行版本。 – gushitong