【问题标题】:Parallelize the function in Python在 Python 中并行化函数
【发布时间】:2020-09-21 19:31:09
【问题描述】:

我有一个下面的函数,我试图使用多处理进行并行化,但我无法让它成功运行。

for d in result_list:
    v=d['content'][0]['template']['module']
    if isinstance(v, list):
        for i, v2 in enumerate(v): 
            df_module,  = normalizeJSON(d,i,v2['id'])
            dim_content_module=dim_content_module.append(df_module, ignore_index=True,sort=False)

    else:
        print('module is not a list')


【问题讨论】:

  • 对于初学者,你为什么用for index in range(len(result))而不是for d in resultindex 不在任何地方使用,除了从列表中检索结果。

标签: python threadpool python-multiprocessing


【解决方案1】:

从多处理模块尝试池如下:-

from multiprocessing import Pool

# function which contain main functional logic
def foo(arg):
    # some processing
    return "return for {}".format(arg)


# function which will invoke multiple processes
def function_which_invokes_multiprocesses(some_arg):
    # pass the number of processes you want to invoke
    with Pool(5) as p:
        invoke the function for each process
        print(foo("some arg"))

【讨论】:

    【解决方案2】:

    result 是列表还是字典?

    使用mapimap或两个函数的async函数会更简单。

    from multiprocessing import Pool
    
    args = [r for r in result]
    with Pool() as pool:
        results = pool.map(worker, args)
    
    
    def worker(d):
        v = d['header'][0]['id']['value']
        if isinstance(v, list):
            for i, v2 in enumerate(v):
                df = function1(d, i, v2['id'])
        return df
    

    【讨论】:

    • result 是其中的 dict 列表
    • 我试过上面的。发生的事情是结果中的每个 dict(这是一个 dict 列表)都由所有线程进行。但我想要的是每个线程并行处理列表中的条目。像线程 1 执行结果 [0],线程 2 执行结果 [1] 等等,但将函数 1 的输出附加到 df
    • @LisaMathew,请发布完整代码或工作示例代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多