我有这段代码:
from multiprocessing import Pool, Manager
import numpy as np
l = Manager().list()
def f(args):
a, b = args
l.append((a, b))
data = [(1,2), (3,4), (5,6)]
with Pool() as p:
p.map(f, data)
x, y = np.transpose(l)
# do something with x and y...
实际上,数据是一个包含大量值的数组,转置操作很长且占用内存。
我想要的是追加" a"和" b"直接列出x和y以避免转置操作。重要的是输出保持数据中的对应关系,如下所示:[[1,3,5],[2,4,6]]
这样做的聪明方法是什么?
答案 0 :(得分:4)
您可以使函数返回值并将它们附加到主进程中,而不是尝试从子进程追加;您不需要关心子流程之间的相互访问(也不需要使用管理器)。
from multiprocessing import Pool
def f(args):
a, b = args
# do something with a and b
return a, b
if __name__ == '__main__':
data = [(1,2), (3,4), (5,6)]
x, y = [], []
with Pool() as p:
for a, b in p.map(f, data): # or imap()
x.append(a)
y.append(b)
# do something with x and y
assert x == [1,3,5]
assert y == [2,4,6]