我正在尝试使用以下代码更新共享对象(adict
)。但它不起作用。它将输入dict
作为输出
编辑:显然,我在这里试图实现的是将数据(列表)中的项目附加到dict列表中。数据项在目录中给出索引
预期产出:{'2': [2], '1': [1, 4, 6], '3': [3, 5]}
注:方法2引发错误TypeError: 'int' object is not iterable
方法1
from multiprocessing import *
def mapTo(d,tree):
for idx, item in enumerate(list(d), start=1):
tree[str(item)].append(idx)
data=[1,2,3,1,3,1]
manager = Manager()
sharedtree= manager.dict({"1":[],"2":[],"3":[]})
with Pool(processes=3) as pool:
pool.starmap(mapTo, [(data,sharedtree ) for _ in range(3)])
from multiprocessing import *
def mapTo(d):
global tree
for idx, item in enumerate(list(d), start=1):
tree[str(item)].append(idx)
def initializer():
global tree
tree = dict({"1":[],"2":[],"3":[]})
data=[1,2,3,1,3,1]
with Pool(processes=3, initializer=initializer, initargs=()) as pool:
pool.map(mapTo,data)```
如果希望反映更改,则需要使用托管列表。因此,以下内容对我很有用:
这是输出:
注意,在使用多处理时,您应该始终使用
if __name__ == '__main__':
保护,并且避免带星号的导入编辑
如果使用Python,则必须执行此重新分配<;3.6,因此将其用于
mapTo
:最后,你没有正确地使用
starmap
/map
,你传递了三次数据,当然,所有的数据都会被计算三次。映射操作应适用于要映射的数据的每个单独元素,因此您需要以下内容:相关问题 更多 >
编程相关推荐