python - 如何并行循环以更改 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)
我的问题是:我该如何进行这项工作?
我只需要使用该函数来并行修改字典中的所有对象。稍后我将保存完整的字典,但我应用的函数不返回任何内容(如果这使事情变得更容易)。
解决方案
您可以通过以下方式ThreadPool
从模块中使用:multiprocess
- 创建字典键列表 (
ls = [a for a in dict.keys()
) - 定义一个函数,该函数给出一个指向 dict 的指针,并且一个键可以进行您想要的更改
- 使用
ThreadPool
'sstarmap()
方法在您创建的列表和 dict 上运行该函数 - 加入并关闭线程池
推荐阅读
- python - 交换熊猫中选定行的列值
- perl - 使用 perl 模块并将变量传递到子例程的问题
- node.js - 如何在nodejs中获取MM中的月份和dd格式的日期
- android - 当我尝试以横向模式打开它时,颤动“应用程序不断停止”消息
- java - 如何调用另一个类超类?
- javascript - 如何比较数组的值,如果它们相等,则使它们为一
- image-processing - 对数分布图像的直方图均衡化
- docker - 从现有的 Dockerfile 派生 + 将 USER 设置为非 root
- python - 从无限 while 循环写入 CSV
- sql - 我的数据库的 oracle 中游标的语法有什么问题?