2016-04-25 51 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