首页 > 解决方案 > 如何并行循环以更改 Python 中字典中的对象?

问题描述

这是我的问题的最小示例:

import concurrent.futures
from functools import partial

# Object class
class obj:
    def __init__(self,tup):
        self.tup = tup

# Function includes attributes in objects of class above
def new(fi,fdic):
    fdic[fi].new = 'work_'+ str(fdic[fi].tup)
    
# Dictionary full of instances of obj above    
dic = {'a':obj(1),
       'b':obj(2),
       'c':obj(3),
       'd':obj(4),
       'e':obj(5),
       'f':obj(6),
      }

partial_new = partial(new, fdic=dic)

现在我想多处理字典中的所有对象(因为我实际上有太多)。下面的代码运行。但它不起作用,因为我实际上需要 ProcessPool (我认为?因为我想并行处理事情)。

with concurrent.futures.ThreadPoolExecutor() as executor:
    for _ in executor.map(partial_new, dic.keys()):
        pass
print(dic['b'].new)

这个不运行:

with concurrent.futures.ProcessPoolExecutor() as executor:
    for _ in executor.map(partial_new, dic.keys()):
        pass
print(dic['b'].new)

我的问题是:我该如何进行这项工作?

我只需要使用该函数来并行修改字典中的所有对象。稍后我将保存完整的字典,但我应用的函数不返回任何内容(如果这使事情变得更容易)。

标签: pythondictionaryfor-loopobjectmultiprocessing

解决方案


您可以通过以下方式ThreadPool从模块中使用:multiprocess

  1. 创建字典键列表 ( ls = [a for a in dict.keys())
  2. 定义一个函数,该函数给出一个指向 dict 的指针,并且一个键可以进行您想要的更改
  3. 使用ThreadPool'sstarmap()方法在您创建的列表和 dict 上运行该函数
  4. 加入并关闭线程池

推荐阅读