2016-04-25 57 views
0

我的多處理模塊有問題。我想用一個for循環遍歷一個字典,這個過程應該爲每個字典做一個工作。用多處理技術做這件事最好的辦法是什麼?Python3用於多處理循環

回答

1

the documentation of the multiprocessing module中有很多可以理解的例子。下面的代碼是基於第一個,f()是你執行的每字典項功能:

from multiprocessing import Pool 

def f(x): 
    return (x[0], x[1]*x[1]) 

if __name__ == '__main__': 
    p = Pool(5) 
    d = {'a':1, 'b':2, 'c':3} 
    print list(d.iteritems()) 
    print(p.map(f, d.iteritems())) 

回報:

[('a', 1), ('c', 3), ('b', 2)] 
[('a', 1), ('c', 9), ('b', 4)] 
+0

感謝您的幫助!這就是我正在尋找的! – Melody