如何从 `Pool.map()` 中解压结果?

How to unpack results from `Pool.map()`?

我有一个函数 (preprocess_fit) 将首先预处理数据集(即平滑、基线校正和过滤掉不良数据)。然后该函数对参数进行初始猜测,然后迭代猜测以找到优化的拟合,然后 returns const1, const2。该函数还计算了一堆其他参数,但在这种情况下它们没有被 returned。

然后我需要在目录中的所有文件(~1000 个文件)上循环此函数。我通过使用包含 for 循环的第二个函数(function)来做到这一点。预处理步骤,尤其是猜测迭代特别耗时。

我想使用 multiprocessing 模块合并函数(函数)并解压常量,然后附加到列表中。 try: except: 包含在内,因为某些文件缺少元数据并且 preprocess_fit 函数失败,我希望在发生这种情况时将 nan 值附加到列表中。

问题: 1)池无法解包功能 2)如果我只 return 来自函数(文件)的 const1,则进程将附加到列表而不是输出。

任何建议都会很棒。

def preprocess_fit(file):
    #applies a number of pre-processing steps based on file metadata
    #optimizes fit starting with an initial guess for a parameter until RMS 
    #is minimized
    #returns constants from fitting process and final “guess” parameter
    return const1, const2

def function(files):
    for file in files:
        const1, const2 = preprocess_fit(file)
    return const1, const2

if __name__ == '__main__':
    files = glob.glob("largedata\*.txt")
    p = Pool(24)
    c1 = []
    c2 = []
    import numpy as np
    try:
        const1, const2 = p.map(function, files)
        c1.append(const1)
        c2.append(const2)
    except:
        c1.append(np.nan)
        c2.append(np.nan)
    p.close()
    p.join()

当您的函数返回多个项目时,您将从 pool.map() 调用中获得结果元组列表。 const1 需要这些元组中的所有第一项,const2 这些元组中的所有第二项。这是 zip 内置函数的工作,它 returns 一个迭代器,它聚合来自作为参数传递的每个可迭代对象的元素。

您必须解压缩列表,以便结果元组成为 zip 函数的参数。然后通过分配给多个变量来解压迭代器:

const1, const2 = zip(*pool.map(function, files))