多处理:同时附加到 2 个列表
Multiprocessing: append to 2 lists simultanously
我有这个代码:
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]]
这样做的明智方法是什么?
您可以使函数 return 的值并在主进程中追加,而不是尝试从子流程追加;你不需要关心子进程之间的相互访问(也不需要使用管理器)。
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]
我有这个代码:
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]]
这样做的明智方法是什么?
您可以使函数 return 的值并在主进程中追加,而不是尝试从子流程追加;你不需要关心子进程之间的相互访问(也不需要使用管理器)。
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]