多处理:同时附加到 2 个列表

aro*_*lle 4 python shared-memory multiprocessing

我有这个代码:

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...
Run Code Online (Sandbox Code Playgroud)

实际上,数据是一个有很多值的数组,转置操作很长,很耗内存。

我想要的是将“a”和“b”直接附加到列表 x 和 y 以避免转置操作。重要的是输出保持数据中的对应关系,如下所示:[[1,3,5], [2,4,6]]

这样做的明智方法是什么?

fal*_*tru 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]
Run Code Online (Sandbox Code Playgroud)