python-多重处理:同时追加到2个列表
作者:互联网
我有以下代码:
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]
有什么聪明的办法做到这一点?
解决方法:
您可以使函数返回值并将其附加到主进程中,而不必尝试从子进程中附加.您无需关心子流程之间的相互访问(也无需使用管理器).
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]
标签:multiprocessing,shared-memory,python 来源: https://codeday.me/bug/20191025/1932095.html